我需要反序列化以下内容:
{
"name": "library",
"contains": [
{
"name: "office",
"contains": []
},
{
"name": "Home",
"contains":[{
"name": "Shelf",
"contains" : []
}]
}]
}
我的类(class)如下所示:
public class Container
{
String containerName;
}
Public class Contains extends Container {
@SerializedName("contains")
@Expose
private List<Container> contains;
}
当我运行代码时,我希望获得一个 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
关于java - 通过继承将 JSON 反序列化为 Java 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35437846/