GSON - 1 parent,多个 children

GSON - 1 parent, multiple children

下面JSON,你会看到有很多objects有一个'groups' child(这些好像都一样),并且这些组有一个名为 'items' 的 child(这些因组的 parent 而异)。

我的问题:

是否有可能使 1 'groups' class 添加到多个 objects 但仍然有正确的 'items' class 被 GSON 解析?

可能是这样的:

public List<Item<T>> items

不确定如何解决这个问题并试图避免写大量冗余 'groups' classes.

提前致谢!

粘贴 JSON 字符串使我超出了字符数限制,因此我将其发布到 pastebin 上。你可以找到它by clicking here

您尝试反序列化的 JSON 的问题是它包含混合元素作为 groups 项,因此不可能只编写一个 POJO 来适应该结构。

事实上,在某些时候你会有这样一个字段:

ArrayList<Group> groups;

但是Group可以在列表中的项目之间更改实际类型,所以此时您可以做的是像这样构建一个通用父亲GenericGroup<T> class:

public class GenericGroup<T> {

    String type;
    String name;
    ArrayList<T> items;

    public ArrayList<T> getItems(){
        return items;
    }

    public static class SomeGroup extends GenericGroup<SomeItem>{}
    public static class SomeOtherGroup extends GenericGroup<SomeOtherItem>{}

}

完成此操作后,您应该为 JSON 字段输入 POJO 模型:

ArrayList<GenericGroup> groups;

现在您已准备好创建所需的每种类型的项目,例如:

public class SomeItemType{

    String someAttribute;
    String someOtherAttribute;
    ...

}

现在到了疯狂的部分,您需要为 class GenericGroup 编写自定义 GSON 解串器:

public class GenericGroupDeserializer implements JsonDeserializer<GenericGroup> {
    @Override
    public GenericGroup deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        String type = json.getAsJsonObject().get("type").getAsString();
        switch (type){
            case "someType":
                return new Gson().fromJson(json.toString(), GenericGroup.SomeGroup.class);
            case "someOtherType":
                return new Gson().fromJson(json.toString(), GenericGroup.SomeOtherGroup.class);
            default:
                return new GenericGroup();
        }
    }
}

最后,在你的 MainActivity 中写下这样的东西:

private Gson mGson = new GsonBuilder()
            .registerTypeHierarchyAdapter(GenericGroup.class, new GenericGroupDeserializer()).create();