将JsonObject解析为Gson的Object列表

时间:2015-03-22 05:35:27

标签: android json gson

我在这个问题上坚持了一段时间 我有一个这样的Json。

{
  "China": [
       "Phanna Nikhom",
    "Ban Na",
    "Ban Ko Pao",
    "Mae Sot"
  ],
  "United States": [
    "Dana",
    "Welaka",
    "Taberg",
    "Maxwell"
  ],
  "India": [
    "Gudur",
    "Farakka",
    "Baramati",
    "Tohana"
  ],
  "Malaysia": [
    "T'aebaek",
    "Hadong",
    "Haesan",
    "Chungju",
    "Chilgok",
    ""
  ],
  "Hong Kong": [
    "Naguilian",
    "San Vicente",
    "Sto Nino",
    "Province of Laguna",
    "Quezon"
  ]
}

我需要将其解析为对象模型列表,如:

Class{
   String country;
   List<String> name;
}

我已经搜索了但是看不到任何类似的解决方案。

请帮忙。 谢谢!

2 个答案:

答案 0 :(得分:0)

我找到了解决方案,我想发布答案,以便在遇到类似问题时帮助其他人: 通过使用这样的迭代器:

ArrayList<CityCountryModel> tListContry = new ArrayList<CityCountryModel>();
Iterator<?> keys = tJsonObject.keys();

while (keys.hasNext()) {
    tModel = new CityCountryModel();
    String key = (String) keys.next();
    tModel.setCountry(key);
    if (tJsonObject.get(key) instanceof JSONArray) {
        String[] tCityList = gson.fromJson(tJsonObject.get(key)
                .toString(), new TypeToken<String[]>() {
        }.getType());
        tModel.setCitys(Arrays.asList(tCityList));
        tListContry.add(tModel);
    }
}

答案 1 :(得分:0)

您也可以为此编写自定义反序列化器。

class CityCountryModelDeserializer implements JsonDeserializer<List<CityCountryModel>> {
    @Override
    public List<CityCountryModel> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        List<CityCountryModel> list = new ArrayList<>();
        for(Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
            List<String> names = new ArrayList<>();
            for(JsonElement e : entry.getValue().getAsJsonArray()) {
                names.add(e.getAsString());
            }
            list.add(new CityCountryModel(entry.getKey(), names));
        }
        return list;
    }
}

然后在Gson对象中注册它:

Type t = new TypeToken<List<CityCountryModel>>(){}.getType();
Gson gson = new GsonBuilder().registerTypeAdapter(t, new CustomDeserializer()).create();
List<CityCountryModel> l = gson.fromJson(new FileReader(new File("file")), t);

输出:

country=China, name=[Phanna Nikhom, Ban Na, Ban Ko Pao, Mae Sot]
country=United States, name=[Dana, Welaka, Taberg, Maxwell]
country=India, name=[Gudur, Farakka, Baramati, Tohana]
country=Malaysia, name=[T'aebaek, Hadong, Haesan, Chungju, Chilgok, ]
country=Hong Kong, name=[Naguilian, San Vicente, Sto Nino, Province of Laguna, Quezon]