Reputation: 1291
Hi how do I deserialize json objects of the type?
{"photo":{"id":5, "url":"http://pics.com/pic1.jpg"}};
Because normally I would create a Class:
public class Photo{
private int id;
private String url;
public Photo(){
}
}
And then just run it using:
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
Photo photo = gson.fromJson(response, Photo.class);
But that just fills everything with nulls. It would work if I the Json was only
{"id":5, "url":"http://pics.com/pic1.jpg"}
Any ideas?
Thanks
Upvotes: 4
Views: 928
Reputation: 599
Create another class that has the Photo class as property
public class PhotoRoot {
private Photo photo;
public void setPhoto(Photo val) {
photo = val;
}
public Photo getPhoto() {
return photo;
}
}
Then Parse it like
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
PhotoRoot photoRoot = gson.fromJson(response, PhotoRoot.class);
Photo yourPhoto = photoRoot.getPhoto();
Regards
Upvotes: 3
Reputation: 274838
Your json structure is not valid. You need to change it to
{"id":5, "url":"http://pics.com/pic1.jpg"}
to match your Photo class.
The reason why {"photo":{"id":5, "url":"http://pics.com/pic1.jpg"}}
doesn't work is that GSON looks for a property called photo
within your Photo class which doesn't exist.
Upvotes: 0