[英]Dynamically tags parsing Json Data using gson
I have a JSoN data like this: 我有一个这样的JSoN数据:
{
"data": {
"noofCity": "1",
"City 1": [
{
"id": "12",
"title": "Delhi"
}
]
},
"success": true
}
Now based on noofCity next tag City 1 will be generated. 现在基于noofCity,将生成下一个标签City 1。 If noofCity will be 2 then there are two tag City 1 and City 2. Then how can I parse it using Json? 如果noofCity将为2,则有两个标记City 1和City2。那么我如何使用Json解析它? Please tell me how can I generate my POJO class structure. 请告诉我如何生成POJO类结构。
Your POJOs should look like below: 您的POJO应该如下所示:
Main POJO for Response: 响应的主要POJO:
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
. 但是,最重要的想法之一是如何对Data
进行反序列化。 You have to prepare your own deserialiser for this, and define way how to fill HashMap
as is shown in the code below: 您必须为此准备自己的反序列化器,并定义如何填充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;
}
}
And now you can deserialise you json 现在您可以反序列化json
Gson gson = new GsonBuilder()
.registerTypeAdapter(Data.class, new DataDeserializer())
.create();
Response test = gson.fromJson(json, Response.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.