Question about Json deserialization using Gson

Hi, how do I deserialize type json objects?

{"photo":{"id":5, "url":"http://pics.com/pic1.jpg"}}; 

Because usually I would create a class:

 public class Photo{ private int id; private String url; public Photo(){ } } 

And then run it using:

  GsonBuilder gsonb = new GsonBuilder(); Gson gson = gsonb.create(); Photo photo = gson.fromJson(response, Photo.class); 

But it just fills everything with zeros. It would work if I were Json only

  {"id":5, "url":"http://pics.com/pic1.jpg"} 

Any ideas?

thanks

+4
source share
2 answers

Create another class with class Photo as property

 public class PhotoRoot { private Photo photo; public void setPhoto(Photo val) { photo = val; } public Photo getPhoto() { return photo; } } 

Then analyze it as

 GsonBuilder gsonb = new GsonBuilder(); Gson gson = gsonb.create(); PhotoRoot photoRoot = gson.fromJson(response, PhotoRoot.class); Photo yourPhoto = photoRoot.getPhoto(); 

Hello

+3
source

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 that {"photo":{"id":5, "url":"http://pics.com/pic1.jpg"}} doesn’t work is because GSON is looking for a property called photo in your Photo class that doesn't exist.

0
source

Source: https://habr.com/ru/post/1341635/


All Articles