我有类似的JSON:

{
  "unknown_field": {
    "field1": "str",
    "field2": "str",
    "field3": "str",
    "field4": "str",
    "field5": "str"
  }, ......
}

I created classes to map this json

public class MyModel implements Serializable {
  private int id;
  private HashMap<String, Model1> models;

  // getters and setter for id and models here
}

and class Model1 is a simple class only with String fields.

但它不起作用.

Edit:JSON format看起来像这样:

{
    "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"
    }, 
    ...
}

推荐答案

(After OP commented that in fact the JSON looks like this, I completely updated the answer.)

Gson 2.0的解决方案+

I just learned that with newer Gson versions this is extremely simple:

GsonBuilder builder = new GsonBuilder();
Object o = builder.create().fromJson(json, Object.class);

The created object is a Map (com.google.gson.internal.LinkedTreeMap), and if you print it, it looks like this:

{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}
...

Solution using a custom deserialiser

(NB:事实证明,除非你使用的是Gson的2.0之前版本,否则你并不是一个真正的自定义反序列化程序.但知道如何执行custom deserialisation (and serialisation) in Gson次还是很有用的,而且这通常可能是最好的方法,这取决于你想如何使用解析的数据.)

所以我们确实在处理随机/可变字段名.(当然,这种JSON格式不是很好;这种数据应该在JSON array之内,在这种情况下,它可以很容易地读入列表.哦,我们仍然可以解析它.)

First, this is how I would model the JSON data in Java objects:

// 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;
    }
}

Then, the parsing. One way to deal with this kind of JSON is to create a custom deserialiser for the top level object (CityList).

Something like this:

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);
    }

}

需要注意的一个关键点是对101的调用,它将重新运行所有顶级字段(名称如"1145"、"1148"等).This Stack Overflow answer帮助我解决了这个问题.

Complete parsing code below. Note that you need to use registerTypeAdapter() to register the custom serialiser.

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);

(Here's a full, executable example that I used for testing. Besides Gson, it uses Guava library.)

Json相关问答推荐

如何在JMESPath中区分空和假?

如何在我的响应模型中修复此问题:[期望的值类型为';Map<;Dynamic,Dynamic&>;,但获得的值类型为';NULL&39;]

Spark-SQL中的from_unixtime函数未能给出正确的输出

Bicep脚本中如何设置弹性池的维护窗口?

如何在 Apache NiFi 中使用 JoltTransformJson 删除流文件或具有空字段的整个对象?

如何使用 Google 表格应用程序脚本将 JSON 中的多个字段提取到 Google 表格中

如何使用 jq 返回此 JSON 文件的文本字段?

避免 KeyError 的默认字典键

为什么在我们有 json_encode 时使用 CJSON 编码

Laravel5 Json 获取文件内容

对象序列化为 JSON(使用 Gson).如何在 UpperCamelCase 中设置字段名称?

JSON.NET JsonConvert 与 .NET JavaScriptSerializer

Jackson 没有使用 @JsonProperty 覆盖 Getter

在 Django 1.9 中,使用 JSONField(本机 postgres jsonb)的约定是什么?

使用 Retrofit 解析动态密钥 Json 字符串

JSON Schema:验证数字或空值

如何让 javascript 从 .json 文件中读取?

MySQL Select JSON 字段属性具有值的位置

带有 Jackson 的不可变 Lombok 注释类

来自 Gson 的 JSON 字符串:删除双引号