繁体   English   中英

使用继承将JSON反序列化为Java对象吗?

[英]Deserialize JSON to Java objects with inheritance?

我需要反序列化以下内容:

{
    "name": "library",
    "contains": [
        {
            "name: "office", 
            "contains": []
        },
        {
            "name": "Home",
            "contains":[{
                "name": "Shelf", 
                "contains" : []
            }]
       }]
} 

我的班级看起来像这样:

public class Container
{
     String containerName;
}
Public class Contains extends Container {
    @SerializedName("contains")
    @Expose
    private List<Container> contains;
}

当我运行代码时,我希望得到一个包含对象来运行我的方法,但不会得到它们。 但是我得到了一个容器对象,无法在Contains类中运行我的方法。

您不需要在这里继承。 只需使用Gson.fromJson()

对象类别

public class Container {
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("contains")
    @Expose
    private List<Container> contains;

    public Container(String name) {
        this.name = name;
        contains = new ArrayList<Container>();
    }

    public void setName(String name) {
        this.name = name;
    }

    public void add(Container c) {
        this.contains.add(c);
    }

    public void setContainerList(List<Container> contains) {
        this.contains = contains;
    }

    public String getName() {
        return name;
    }

    public List<Container> getContainerList() {
        return this.contains;
    }
}

public static void main(String[] args) {
    Container lib = new Container("library");
    Container office = new Container("office");

    Container home = new Container("Home");
    Container shelf = new Container("Shelf");

    home.add(shelf);
    lib.add(office);
    lib.add(home);

    Gson gson = new Gson();
    // Serialize
    String json = gson.toJson(lib);

    // Deserialize
    Container container = gson.fromJson(json, Container.class);

    System.out.println(container.getName());
    for (Container c : container.getContainerList()) {
        System.out.println("-- " + c.getName());
    }
}

产量

library
-- office
-- Home

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM