使用 gson 动态标记解析 Json 数据

Dynamically tags parsing Json Data using gson

我有一个这样的 JSoN 数据:

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


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

现在将基于noofCity 生成下一个标签City 1。如果 noofCity 为 2,则有两个标签 City 1 和 City 2。那么我如何使用 Json 解析它?请告诉我如何生成我的 POJO class 结构。

您的 POJO 应如下所示:

响应的主要 POJO:

public class Response {

    Data data;

    boolean success;
}

对于数据

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;
    }
}

对于城市

public class City {
    int id;
    String title;
}

但最重要的想法之一是如何反序列化 Data。您必须为此准备自己的解串器,并定义如何填充 HashMap 的方式,如下面的代码所示:

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;
    }
}

现在你可以反序列化你了 json

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