How to use gson 2.0 on - onResponse from Retrofit 2.0

I am making an http call using the new 2.0 modification, and getting a callback, I want to use the gson 2.0 library to parse this json obj and be able to do

jsonData.sector[2].sectorOne 

this is my callback:

 retrofitApi.Factory.getInstance().getCallData().enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { } catch (IOException e) { e.printStackTrace(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Log.d("myLogs", "failed to Retrive Data"); Log.d("myLogs", "becouse: "+t); largeTextVar.setText("failed: " + t); } }); 

so my callback will look like

 { "data": { "sector": [ [ { "scanned": false, "sectorOne": "", "sectorTwo": "", "sectorThree": "" }, { "scanned": false, "sectorOne": "", "sectorTwo": "", "sectorThree": "" } ] ] }, "curserLocation": { "elevation": 30, "horizontal": 105 } } 

I use:

 compile 'com.squareup.retrofit2:retrofit:2.0.1' compile 'com.squareup.retrofit2:converter-gson:2.0.1' 

I searched everywhere how to do it, but I could not find a simple solution for this, what is the easiest and easiest way to achieve this?

-one
json android gson retrofit
source share
1 answer

Okey I will explain how to convert the JSON response to POJO :

First of all, you have to create a POJO class in: JSON Schema 2 POJO

  • Insert your example JSON response
  • Select source type: JSON
  • annotation style: gson

It will create a POJO class for you.

Then in your onResponse method:

  @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if(response.code()==200){ Gson gson = new GsonBuilder().create(); YourPOJOClass yourpojo=new YourPOJOClass (); try { yourpojo= gson.fromJson(response.body().toString(),YourPOJOClass.class); } catch (IOException e) { // handle failure to read error Log.v("gson error","error when gson process"); } } 

Remember to add compile 'com.google.code.gson:gson:2.4'

Another way to do this is to create a pojo class as shown above.

In your API:

 @POST("endpoint") public Call<YourPOJOClass> exampleRequest(); 

When called:

  OkHttpClient okClient = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).build(); Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") .create(); Retrofit client = new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create(gson)) .client(okClient) .build(); YourApiClass service = client.create(YourApiClass.class); Call<YourPOJOClass> call=service.exampleRequest(); call.enqueue(new Callback<YourPOJOClass>() { @Override public void onResponse(Call<YourPOJOClass> call, Response<YourPOJOClass> response) { //already Gson convertor factory converted your response body to pojo response.body().getCurserLocation(); } @Override public void onFailure(Call<YourPOJOClass> call, Throwable t) { } }); 
0
source share

All Articles