How to get JSON ARRAY and JSON object response fro

2019-06-02 01:54发布

问题:

I have worked with file upload using retrofit. It works fine. But how do handle the retrofit success response. and How do i create serialization model class for below Json array and Json object.

{
        "result": [{
            "fileId": 869,
            "status": 1,
            "pcData": {
                "id": 652,
                "filename": "IMG_20161122_175344.jpg",
                "filepath": "uploads\/peoplecaddie\/files\/1743_1481109145_IMG_20161122_175344.jpg"
            }
        }]
    }

Here is My call method

Call<ServerResponse> call = service.upload("817b6ce98fd759e7f148b948246df6c1", map, idReq, fileCountReq, fileTypeReq, platformReq, externalIDReq);
        call.enqueue(new Callback<ServerResponse>() {
            @Override
            public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
                ServerResponse serverResponse = response.body();
                Log.e("serverResponse", "serverResponse" + serverResponse.toString());
                if (serverResponse != null) {


                }

            }

            @Override
            public void onFailure(Call<ServerResponse> call, Throwable t) {

            }
        });

I am having doubt that how to implement ServerResponse model class with JSON array field, JSON object field and string values which is inside JSON object.

public class ServerResponse {
    //How to handle my response with in this model class.

}

Please help me to solve this. Thanks in advance.

回答1:

Create Classes like below and use ServerResponse as the model class while call,

ServerResponse.class

public class ServerResponse {

    @SerializedName("result")
    private ArrayList<Result> mResult;

    public ArrayList<Result> getResult() {
        return mResult;
    }

    public void setResult(ArrayList<Result> result) {
        mResult = result;
    }
}

Result.class

public class Result {

    @SerializedName("fileId")
    private int mFileId;

    @SerializedName("status")
    private String mstatus;

    @SerializedName("pcData")
    private PcData mPcData;

    public int getFileId() {
        return mFileId;
    }

    public void setFileId(int fileId) {
        mFileId = fileId;
    }

    public String getMstatus() {
        return mstatus;
    }

    public void setMstatus(String mstatus) {
        this.mstatus = mstatus;
    }

    public PcData getPcData() {
        return mPcData;
    }

    public void setPcData(PcData pcData) {
        mPcData = pcData;
    }
}

PcData.class

private class PcData {

    @SerializedName("id")
    private int mId;

    @SerializedName("filename")
    private String mFileName;

    @SerializedName("filepath")
    private String mFilePath;

    public int getId() {
        return mId;
    }

    public void setId(int id) {
        mId = id;
    }

    public String getFileName() {
        return mFileName;
    }

    public void setFileName(String fileName) {
        mFileName = fileName;
    }

    public String getFilePath() {
        return mFilePath;
    }

    public void setFilePath(String filePath) {
        mFilePath = filePath;
    }
}

And your call should be like this:

Call<ServerResponse> call = service.upload("817b6ce98fd759e7f148b948246df6c1", map, idReq, fileCountReq, fileTypeReq, platformReq, externalIDReq);
    call.enqueue(new Callback<ServerResponse>() {
        @Override
        public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
            ServerResponse serverResponse = response.body();
            if (serverResponse != null) {
                //below is how you can get the list of result
                List<Result> resultList = response.getResult();
            }

        }

        @Override
        public void onFailure(Call<ServerResponse> call, Throwable t) {

        }
    });


回答2:

You can declare your service using below code

Call<ServerResponse<ArrayList<YourModel>>>

and

public class ServerResponse<T> {

private T result;
public T getResult() {
    return data;
}

public void setResult(T data) {
    this.data = data;
}


}

then you will receive ServerResponse in onResponse Method and get lsit by calling method getResult of SErverResponse.



回答3:

You can use RxJava with Retrofit

First create Pojo for your JSON Response, you can use http://www.jsonschema2pojo.org/ for doing this.

Then Create a Singleton class for Retrofit

    public class RetroSingleton {
    private static RetroSingleton ourInstance = new RetroSingleton();

    public static RetroSingleton getInstance() {
        return ourInstance;
    }

    private RetroSingleton() {
    }

    public RestApi getRestApi() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(logging);
        OkHttpClient client = httpClient.build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ConstUrl.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();

        return retrofit.create(RestApi.class);
    }
}

Then Create a Interface where you can define all your methods for doing network calls

    public interface RestApi {

/*
*@POST or @GET type of call

*/
    @POST("url")// either full url or path of url
    Observable<YourResponsePojo> methodName(@Query("nameOfField") String field);

    @GET("url")
    Observable<YourResponsePojo> methodName();

}

Finally for using the call you can use

RetroSingleton.getInstance().getRestApi().methodName()
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<YourResponsePojo>() {
            @Override
            public void onCompleted() {
                hideProgressDialog();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(YourResponsePojo yourResponsePojo) {
// yourResponsePojo contains all of your response body
            }
        });