简体   繁体   中英

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.

You don't need inheritance here. Just use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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