一尘不染

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

java

我有与此类似的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"
    }, 
    ...
}

阅读 329

收藏
2020-03-22

共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}, 
 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 city
public class City    {
    String citiesId;
    String city;
    String regionName;
    // and so on
}

// top-level object, containing info for lots of cities
public class CityList  {
    List<City> cities;

    public CityList(List<City> cities) {
        this.cities = cities;
    }
}

然后,解析。处理此类JSON的一种方法是为顶级对象(CityList)创建自定义反序列化器。

像这样:

public class CityListDeserializer implements JsonDeserializer<CityList> {

    @Override
    public CityList deserialize(JsonElement element, Type type, JsonDeserializationContext context) throws JsonParseException {
        JsonObject jsonObject = element.getAsJsonObject();
        List<City> cities = new ArrayList<City>();
        for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
            // For individual City objects, we can use default deserialisation:
            City city = context.deserialize(entry.getValue(), City.class); 
            cities.add(city);
        }
        return new CityList(cities);
    }

}

需要注意的关键点是重新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);
2020-03-22