Json Parsing With Retrofit
Solution 1:
This is how I solved this problem, by creating empty constructors.
Feed.class
publicclassFeed{
private List<Result> results;
publicFeed(){}
public List<Result> getFeed(){
returnthis.results;
}
publicvoidsetFeed(List<Result> results) {
this.results = results;
}
}
Result.class
publicclassResult{
privateString description_eng;
privateString img_url;
privateString title_eng;
public Result(){}
//getters and setters
}
GetApi.class
publicinterfaceGetApi {
@GET("/api.json")publicvoidgetData(Callback<Feed> response);
}
Solution 2:
Retrofit uses Gson by default to convert HTTP bodies to and from JSON. If you want to specify behavior that is different from Gson's defaults (e.g. naming policies, date formats, custom types), provide a new Gson instance with your desired behavior when building a RestAdapter.
Gson can not automatically deserialize the pure inner classes since their no-args constructor also need a reference to the containing Object which is not available at the time of deserialization. You can address this problem by either making the inner class static or by providing a custom InstanceCreator for it. Here is an example:
publicclassA {
publicString a;
classB {
publicString b;
publicB() {
// No args constructor for B
}
}
}
NOTE: The above class B can not (by default) be serialized with Gson.
You should read more about GSON library
Solution 3:
@Ye Min Htut Actually, even better is to write Feed class with generics.
publicclassFeedList<T>{
private List<T> feeds;
publicFeed() {
}
public List<T> getFeed(){
returnthis.feeds;
}
publicvoidsetFeed(List<T> results) {
this.feeds = feeds;
}
}
and if there is something similar with only one object, than you can remove List part and get/set single object.
Now you can call FeedList<Result>
or with whatever object you want.
GetApi.class
publicinterfaceGetApi {
@GET("/api.json")publicvoidgetData(Callback<FeedList<Result>> response);
}
Solution 4:
@Ye Min Htut I will suggest you to make Model/POJO classes using ROBOPOJO Generator It will generate All model classes for you, you don't need to make it by your self, Will also help you in future while creating model class. It just need JSON string and click will make your job done
Post a Comment for "Json Parsing With Retrofit"