Nurzhan Nogerbek
Nurzhan Nogerbek

Reputation: 5246

How to parse JSON with Retrofit

I have problem with parsing Json in Retrofit. My URL: http://192.168.0.102:8000/api/get_services?keyword=someword

Someword here is the word which user writes in dialog window.

I need only

Here I have null in coords. I want to take the results and show it Google Maps.

What's wrong? How I can fix problem?

JSON:

JSON Data Screenshot

LocationActivity.java

private void showInputDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        final LayoutInflater inflater = this.getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_search, null);
        builder.setView(dialogView);

        final EditText inputSearch = (EditText) dialogView.findViewById(R.id.input_service);
        inputSearch.setInputType(InputType.TYPE_CLASS_TEXT);

        builder.setPositiveButton("Поиск", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                final String SearchPosition = inputSearch.getText().toString();

                if (SearchPosition.matches("")) { //Check if EditText is empty
                    Toast.makeText(getApplicationContext(), "Space is empty!", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    NetworkFactory.getInstance().getApiCall().getPosition(new Words(SearchPosition), new Callback<PositionResponse>() {
                        @Override
                        public void success(PositionResponse positionResponse, Response response) {
                            Log.d("Result: ", Arrays.toString(positionResponse.getPosition()).replaceAll("\\[|\\]", ""));
                            if (positionResponse.getPosition() == null) {
                                //Toast Message
                                Toast.makeText(getApplicationContext(), "There is no such result! Try again!", Toast.LENGTH_LONG).show();
                            } else {
                                String mLatLng = Arrays.toString(positionResponse.getPosition()).replaceAll("\\[|\\]", "");

                                String[] arrayLatLng = mLatLng.split(","); //separate out lat and lon
                                LatLng positionLatLon = new LatLng(Double.parseDouble(arrayLatLng[0]), Double.parseDouble(arrayLatLng[1])); //create the LatLng object

                                mGoogleMap.addMarker(new MarkerOptions().position(positionLatLon)
                                        .title("Result")
                                        .snippet("Result of search: " + SearchPosition)
                                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_location)));

                                CameraPosition cameraPosition = new CameraPosition.Builder().target(positionLatLon).zoom(17).build();
                                mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                            }
                        }

                        @Override
                        public void failure(RetrofitError error) {
                            error.toString();
                        }
                    });
                }
            }
        });
        builder.show();
    }

NetworkFactory.java

public class NetworkFactory {
    public static final String API_URL = "http://192.168.0.102:8000";
    private static NetworkFactory ourInstance = new NetworkFactory();
    private ApiCalls apiCalls;

    private NetworkFactory() {
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(API_URL)
                .build();
        apiCalls = restAdapter.create(ApiCalls.class);
    }

    public static NetworkFactory getInstance() {
        return ourInstance;
    }

    public ApiCalls getApiCall() {
        return apiCalls;
    }
}

ApiCalls.java

    public interface ApiCalls {
        @GET("/api/get_services")
        void getPosition(@Query("keyword") Words words, Callback<PositionResponse> responseCallback);
    }

PositionResponse.java

public class PositionResponse {
    private double[] coords;
    private String address;
    private String company_name;

    public double[] getPosition() {
        return coords;
    }

    public void setPosition(double[] coords) {
        this.coords = coords;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCompanyName() {
        return company_name;
    }

    public void setCompanyName(String company_name) {
        this.company_name = company_name;
    }
}

Upvotes: 0

Views: 792

Answers (2)

SekthDroid
SekthDroid

Reputation: 140

As dabluck told you, you web service is responding with a JSONArray, so you will need to wrap your response around a List (for example).

Something like this should work:

public class ListPositionResponse { 

    private List<PositionResponse> service_list;
    public ListPositionResponse(List<PositionResponse> service_list){
        this.service_list = service_list;
    }
} 

So you retrofit call will be:

public interface ApiCalls { 
        @GET("/api/get_services") 
        void getPosition(@Query("keyword") Words words, Callback<ListPositionResponse> responseCallback);
}

Hope it will help you.

EDIT: To get the coords for each PositionResponse:

public class ListPositionResponse { 

        private List<PositionResponse> service_list;
        public ListPositionResponse(List<PositionResponse> service_list){
            this.service_list = service_list;
        }

        public List<PositionResponse> getPositions(){
            return this.service_list;
    } 



// And In your Activity
public void showCoords(ListPositionResponse positionResponse){
    for(PositionResponse position : positionResponse.getPositions()){
        doSomethingWithPosition(position);
    }
}


public void doSomethingWithPosition(PositionResponse position){
    double[] coords = position.getPosition();
    LatLng positionLatLon = new LatLng(double[0], double[1]);
}

Upvotes: 1

dabluck
dabluck

Reputation: 1181

your positionresponse object isn't correct. you need a servicelist object in there. use jsonschema2pojo.org to generate objects and try again

Upvotes: 0

Related Questions