我需要反序列化以下内容:
{
"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类中运行我的方法。
答案 0 :(得分:0)
这里不需要继承。只需使用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