【问题标题】:Dynamically tags parsing Json Data using gson使用 gson 动态标记解析 Json 数据
【发布时间】:2015-04-30 11:29:52
【问题描述】:

我有一个这样的 JSON 数据:

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


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

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

【问题讨论】:

  • 如果 noofCity 的值为 2,您是否会有两个数组 City 1City 2?对吗?
  • @konrad Krakowiak 是的,city1 和 city 2 也将再次成为数组
  • 您必须输入“City 1”和“2”。如果未找到“City 2”,json 解析器将忽略它并且“City 2”引用将为空。 (并使用 Gson)
  • @wisemann 我猜他不仅关心"City 1" and "City 2"。他担心动态处理它,因为这个列表可能会超出这个范围。
  • @kunu 你是对的.. 这个列表可以根据 noofCity 增长。

标签: android json gson


【解决方案1】:

您的 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);

【讨论】:

  • Krakowiask .. 感谢您的回答...您的回答对我来说很好。再次感谢....
猜你喜欢
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 2011-11-30
  • 2017-08-23
  • 2011-08-13
  • 2018-04-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多