如何反序列化包含相同键名但使用不同类型的 JSON 文件(使用 Google JSON)?

How to deserialize a JSON file ( using Google JSON) consisting of same key name but uses different type?

考虑以下 JSON 文件:

{
    "version": "1.0",
    "firstData": {
        "meta": "this is string",
        "version": "1"
    },
    "SecondData": {
        "meta": ["string1", "string2", "string3"],
        "version": "1"
    },
    "ThirdData": {
        "meta": true,
        "version": "1"
    },
    "FourthData": {
        "meta": [true, false, false, true],
        "version": "1"
    },
    "FifthData": {
        "meta": [{
            "meta": "string",
            "version": "2"
        },
        {
            "meta": ["string1","string2"],
            "version": "2"
        }]
        "version": "1"
    }

}

可以看出,"meta"属性有不同的数据类型,有时是String,有时是ArrayOfString,有时是Boolean等

由于我的 JSON 文件有多个数据, 我希望它遵循以下结构:

class information
{
String version;
HashMap<String,Data> details;
}
class Data
{
 variable meta;
String version;
}

如何创建相应的 POJO 并使用 Google GSON 反序列化它?

只需将您的 meta 定义为 JsonElement。然后你将有排序方法,如:getAsStringgetAsBooleangetAsJsonObjectgetAsJsonArray、...,并且你还可以在找出什么后再次反序列化它是类型。

所以你的 class 可能看起来像:

public class SomeClass {
    private int version;
    private JsonElement meta;

    //getters and setters and other stuff
}

编辑:更多阐述和实施

定义两个classes:GeneralItemGeneralData

class GeneralItem
{
    public final int version;
    public final JsonElement meta;
}
class GeneralData
{
    public final String version;
    public final Map<String, GeneralItem> items;

    public GeneralData(String version, Map<String, GeneralItem> items)
    {
        this.version = version;
        this.items = items;
    }
}

然后我们为 GeneralData:

定义自定义反序列化器
class GeneralDataDeserializer implements JsonDeserializer<GeneralData>
{

    @Override
    public GeneralData deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
    {
        final JsonObject object = json.getAsJsonObject();
        final String version = object.get("version").getAsString();
        object.remove("version");
        HashMap<String, GeneralItem> items = new HashMap<>(object.size());
        for (Map.Entry<String, JsonElement> item : object.entrySet())
            items.put(item.getKey(), context.deserialize(item.getValue(), GeneralItem.class));
        return new GeneralData(version, items);
    }
}

最终将反序列化器注册到我们的 gson 实例并获取数据:

final Gson gson = new GsonBuilder()
        .registerTypeAdapter(GeneralData.class, new GeneralDataDeserializer())
        .create();

final String json = "your json here";
final GeneralData data = gson.fromJson(json, GeneralData.class);
System.out.println(data.items.get("firstData").meta.getAsString());
//other parts you want

(注意构造函数、getter和setter、错误检查等为简洁起见被删除)