简体   繁体   中英

Dynamically tags parsing Json Data using gson

I have a JSoN data like this:

{
   "data": {
      "noofCity": "1",


      "City 1": [
         {
            "id": "12",
            "title": "Delhi"
         }
      ]
   },
   "success": true
}

Now based on noofCity next tag City 1 will be generated. If noofCity will be 2 then there are two tag City 1 and City 2. Then how can I parse it using Json? Please tell me how can I generate my POJO class structure.

Your POJOs should look like below:

Main POJO for Response:

public class Response {

    Data data;

    boolean success;
}

For Data

public class Data {

    int noofCity;
    Map<String, List<City>> cityMap;


    void put(String key, List<City> city){
        if(cityMap == null){
            cityMap = new HashMap<>();
        }
        cityMap.put(key, city);
    }


    public void setNoofCity(int noofCity) {
        this.noofCity = noofCity;
    }

    public int getNoofCity() {
        return noofCity;
    }
}

For City

public class City {
    int id;
    String title;
}

But one of the most important think is a way how to deserialise Data . You have to prepare your own deserialiser for this, and define way how to fill HashMap as is shown in the code below:

public class DataDeserializer implements JsonDeserializer<Data> {

    @Override
    public Data deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        Data result  = new Data();
        Gson gson = new Gson();
        JsonObject jsonObject=  json.getAsJsonObject();
        result.setNoofCity(jsonObject.get("noofCity").getAsInt());

        for(int i =1; i<=result.getNoofCity() ; i++ ){
           List<City> cities=  gson.fromJson(jsonObject.getAsJsonArray("City "+ i), List.class);
            result.put("City "+ i, cities);
        }
        return result;
    }
}

And now you can deserialise you json

 Gson gson = new GsonBuilder()
            .registerTypeAdapter(Data.class, new DataDeserializer())
            .create();
 Response test = gson.fromJson(json, Response.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM