Gson and Complex Objects with headers?

90 views
Skip to first unread message

FM29

unread,
Feb 28, 2011, 7:00:48 AM2/28/11
to google-gson
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

Angel Aguilera

unread,
Feb 28, 2011, 2:27:44 PM2/28/11
to googl...@googlegroups.com

As a workaround (not very elegant, though) I think you could wrap the
"Photo" class in another object with a "photo" attribute:

public class PhotoWrapper {
private Photo photo;

(setters/getters...)
}

public class Photo {
(the same as your example)
}

Then you should deserialize into objects of class "PhotoWrapper", and
you can access the inner "photo" attribute via a getter.
Hope this works...

Joel

unread,
Apr 13, 2011, 5:34:33 AM4/13/11
to google-gson
Another approach is that you can do the mixing with the Gson Streaming
parser. See https://sites.google.com/site/gson/streaming for an
example.

On Feb 28, 12:27 pm, Angel Aguilera <angel.aguil...@gmail.com> wrote:
Reply all
Reply to author
Forward
0 new messages