Here is an example line:

{ "code":200, "err":"", "timestamp":1459855918, "data":{ "city":[ { "cityid":3877, "cityname":"", "districts":[ {"id":1245, "name":"", "sort":0}, {"id":1257,"name":"","sort":0}, {"id":1461,"name":"","sort":0}, {"id":1338,"name":"","sort":0} ] }, { "cityid":2263, "cityname":"", "districts":[ {"id":1223,"name":"","sort":0}, {"id":1203,"name":"","sort":8}, {"id":1048,"name":"","sort":8}, {"id":1205,"name":"","sort":999} ] } ] } } 

POJO class:

 public class ObjectGetDictionary { private int code; private String err; private long timestamp; private List<city> data; //геттеры + сеттеры class city { private int cityid; private String cityname; private List<district> districts; //геттеры + сеттеры class district { private int id; private String name; private int sort; //геттеры + сеттеры district(){}; } city(){}; } ObjectGetDictionary(){}; } ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); ObjectGetDictionary res = mapper.readValue(content, ObjectGetDictionary.class); 

How are such complex objects usually converted?

  • 2
    As if classes are always called with a capital letter. - MrTrojan 4:38 pm
  • In general, about how you: a model is made for all levels of nesting. - Nofate
  • You can use the generator - jsonschema2pojo.org - enzo

1 answer 1

as an option (in general):

1. Create a Response class

like this:

 class Response { private int code; private String errorMessage; private Timestamp timestamp; private String data; // getters and setters } 

2. Create a City class

 class City { @SerializedName("cityId"); private int id; @SerializedName("cityname"); private int name; private List<District> districtList; // getters and setters } 

3. Create a District class

 class District { private int id; private String name; private int sort; // getters and setters } 

4. We deserialize:

We need JSONObject and Gson either from Google

Through JSONObject we get from the Response line a JSON object with which we pull the data field. We check the presence of the city field, pull out a list of cities from it. We twist the list of cities in a loop and simultaneously deserialize into POJO:

 JSONObject data = response.get("data"); if (data.has("city")) { JSONArray city = data.get("city"); Gson gson = new Gson(); // цикл по city // десериализуем City city = gson.fromJson(object, City.class); // ... } 
  • Question: Why did we specify the fields in the city class that correspond to the Json @SerializedName ("") fields, but not to the District? - mr. Ball
  • then to match the fields whose names are different (JSON <-> POJO), in the District everything is ok with names and fields - Evgeny Lebedev