简体   繁体   English

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

[英]Deserialize JSON to Java objects with inheritance?

I need to deserialize the following: 我需要反序列化以下内容:

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

My class looks like this: 我的班级看起来像这样:

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

How is it that when I run my code, I am hoping to get a contains object to run my methods it won't get me them. 当我运行代码时,我希望得到一个包含对象来运行我的方法,但不会得到它们。 But I get a container object and can't run my methods from within my Contains class. 但是我得到了一个容器对象,无法在Contains类中运行我的方法。

You don't need inheritance here. 您不需要在这里继承。 Just use Gson.fromJson() . 只需使用Gson.fromJson()

Object class 对象类别

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

Code

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

Output 产量

library
-- office
-- Home

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

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