如何使用Gson解码未知字段的JSON?

我有与此类似的JSON:


{

  "unknown_field": {

    "field1": "str",

    "field2": "str",

    "field3": "str",

    "field4": "str",

    "field5": "str"

  }, ......

}

我创建了一些类来映射这个json


public class MyModel implements Serializable {

  private int id;

  private HashMap<String, Model1> models;


  // getters and setter for id and models here

}

而Model1类是仅包含String字段的简单类。


但这是行不通的。


编辑:JSON格式如下所示:


{

    "1145": {

        "cities_id": "1145",

        "city": "Nawanshahr",

        "city_path": "nawanshahr",

        "region_id": "53",

        "region_district_id": "381",

        "country_id": "0",

        "million": "0",

        "population": null,

        "region_name": "Punjab"

    },

    "1148": {

        "cities_id": "1148",

        "city": "Nimbahera",

        "city_path": "nimbahera",

        "region_id": "54",

        "region_district_id": "528",

        "country_id": "0",

        "million": "0",

        "population": null,

        "region_name": "Rajasthan"

    }, 

    ...

}



开心每一天1111
浏览 243回答 1
1回答

扬帆大鱼

Gson 2.0+的解决方案我刚刚了解到,使用更新的Gson版本,这非常简单:GsonBuilder builder = new GsonBuilder();Object o = builder.create().fromJson(json, Object.class);创建的对象是一个Map(com.google.gson.internal.LinkedTreeMap),如果您打印它,它看起来像这样:{1145={cities_id=1145, city=Nawanshahr, city_path=nawanshahr, region_id=53, region_district_id=381, country_id=0, million=0, population=null, region_name=Punjab},&nbsp;&nbsp;1148={cities_id=1148, city=Nimbahera, city_path=nimbahera, region_id=54, region_district_id=528, country_id=0, million=0, population=null, region_name=Rajasthan}...使用自定义解串器的解决方案(注意:除非您坚持使用Gson 2.0之前的版本,否则您并不是真正的自定义反序列化器。但是了解如何在Gson中进行自定义反序列化(和序列化)仍然很有用,并且通常最佳方法,具体取决于您要如何使用解析后的数据。)因此,我们确实在处理随机/可变字段名称。(当然,这种JSON格式不是很好;这种数据应该放在JSON数组中,在这种情况下,可以很容易地将其读入List。哦,我们仍然可以解析它。)首先,这是我如何在Java对象中对JSON数据建模:// info for individual citypublic class City&nbsp; &nbsp; {&nbsp; &nbsp; String citiesId;&nbsp; &nbsp; String city;&nbsp; &nbsp; String regionName;&nbsp; &nbsp; // and so on}// top-level object, containing info for lots of citiespublic class CityList&nbsp; {&nbsp; &nbsp; List<City> cities;&nbsp; &nbsp; public CityList(List<City> cities) {&nbsp; &nbsp; &nbsp; &nbsp; this.cities = cities;&nbsp; &nbsp; }}然后,解析。处理此类JSON的一种方法是为顶级对象(CityList)创建自定义反序列化器。像这样:public class CityListDeserializer implements JsonDeserializer<CityList> {&nbsp; &nbsp; @Override&nbsp; &nbsp; public CityList deserialize(JsonElement element, Type type, JsonDeserializationContext context) throws JsonParseException {&nbsp; &nbsp; &nbsp; &nbsp; JsonObject jsonObject = element.getAsJsonObject();&nbsp; &nbsp; &nbsp; &nbsp; List<City> cities = new ArrayList<City>();&nbsp; &nbsp; &nbsp; &nbsp; for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // For individual City objects, we can use default deserialisation:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; City city = context.deserialize(entry.getValue(), City.class);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cities.add(city);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return new CityList(cities);&nbsp; &nbsp; }}需要注意的关键点是重新jsonObject.entrySet()调出所有顶级字段(名称如“ 1145”,“ 1148”等)的调用。这个堆栈溢出的答案帮助我解决了这个问题。完成下面的解析代码。请注意,您需要使用registerTypeAdapter()注册自定义序列化程序。GsonBuilder builder = new GsonBuilder();builder.registerTypeAdapter(CityList.class, new CityListDeserializer());Gson gson = builder.setFieldNamingPolicy(LOWER_CASE_WITH_UNDERSCORES).create();CityList list = gson.fromJson(json, CityList.class);(这是我用来测试的完整的可执行示例。除了Gson之外,它还使用Guava库。)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java