Reputation: 175
I have a typical Retrofit API request:
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(URL)
.build();
ApiEndpointInterface api = restAdapter.create(ApiEndpointInterface.class);
api.getToken('1', new Callback<DefaultResponse>() {
@Override
public void success(DefaultResponse json, Response response) {
//
}
@Override
public void failure(RetrofitError response) {
//
}
});
And the returned JSON is:
{"success":true,"data":{"token_id":"pPt9AKl0Cg","token_key":"8ax224sFrJZZkStAQuER"}}
How can I parse this JSON? It seems wrong/tedious to create a new model class for each different response across my app. Is there a better way to do it?
Upvotes: 1
Views: 1133
Reputation: 6334
you should write your model class like below
public class MyResponseModel {//write setters and getters.
private boolean success;
private DataModel data;
public static class DataModel {
private String token_id;
private String token_key;
}
}
now in your getToken()
method should look like this
getToken('1', Callback<MyResponseModel> response);
retrofit
will parse the response and convert it to the class above.
Upvotes: 2
Reputation: 4993
Try this code,
JsonElement je = new JsonParser().parse(s);
JsonObject asJsonObject = je.getAsJsonObject();
JsonElement get = asJsonObject.get("data");
System.out.println(s + "\n" + get);
JsonObject asJsonObject1 = get.getAsJsonObject();
JsonElement get1 = asJsonObject1.get("token_id");
System.out.println(get1);
JsonElement get2 = asJsonObject1.get("token_key");
System.out.println(get2);
Upvotes: 0