i\'m doing an http call using the new retrofit 2.0, and getting a callback, i want to use gson 2.0 library to parse that json obj and to be able to do
json
Okey i will explain how to convert JSON
response to POJO
:
First of all you must create a POJO class in : JSON Schema 2 POJO
JSON
responseIt will generate 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");
}
}
Dont forget to add compile 'com.google.code.gson:gson:2.4'
Another way to do this : create a pojo class like in above.
In your API :
@POST("endpoint")
public Call<YourPOJOClass> exampleRequest();
When calling this :
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) {
}
});