如何使用Retrofit解析JSON

时间:2015-05-02 23:49:10

标签: java android json retrofit android-parser

我在Retrofit中解析Json时遇到问题。 我的网址:http://192.168.0.102:8000/api/get_services?keyword=someword

这里的某些词是用户在对话窗口中写的词。

我只需要

  • COORDS
  • 地址
  • COMPANY_NAME

这里我在coords中有空。我想拍摄结果并显示谷歌地图。

出了什么问题?我怎么解决问题?

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;
    }
}

2 个答案:

答案 0 :(得分:1)

正如dabluck告诉你的那样,你的Web服务正在使用JSONArray进行响应,因此你需要将你的响应包装在一个List中(例如)。

这样的事情应该有效:

public class ListPositionResponse { 

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

所以你改装电话会是:

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

希望它会对你有所帮助。

编辑:获取每个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]);
}

答案 1 :(得分:0)

您的位置响应对象不正确。你需要一个servicelist对象。使用jsonschema2pojo.org生成对象并重试