我有这样的JSoN数据:
{
"data": {
"noofCity": "1",
"City 1": [
{
"id": "12",
"title": "Delhi"
}
]
},
"success": true
}
现在基于noofCity下一个标签将生成城市1。如果noofCity为2,则有两个标记City 1和City 2.那么我如何使用Json解析它?请告诉我如何生成我的POJO类结构。
答案 0 :(得分: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);