我把谷歌的Gson看作是一个潜在的JSON插件。任何人都可以就如何从此JSON字符串生成Java提供某种形式的指导吗?
Google Gson支持泛型和嵌套bean。in JSON 表示一个数组,应映射到 Java 集合(如 List
)或仅映射到普通的 Java 数组。IN JSON 表示一个对象,应该映射到 Java Map
或只是一些 JavaBean 类。[]
{}
您有一个具有多个属性的 JSON 对象,该属性表示完全相同类型的嵌套对象的数组。这可以通过以下方式使用Gson进行解析:groups
package com.stackoverflow.q1688099;
import java.util.List;
import com.google.gson.Gson;
public class Test {
public static void main(String... args) throws Exception {
String json =
"{"
+ "'title': 'Computing and Information systems',"
+ "'id' : 1,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Level one CIS',"
+ "'id' : 2,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Intro To Computing and Internet',"
+ "'id' : 3,"
+ "'children': 'false',"
+ "'groups':[]"
+ "}]"
+ "}]"
+ "}";
// Now do the magic.
Data data = new Gson().fromJson(json, Data.class);
// Show it.
System.out.println(data);
}
}
class Data {
private String title;
private Long id;
private Boolean children;
private List<Data> groups;
public String getTitle() { return title; }
public Long getId() { return id; }
public Boolean getChildren() { return children; }
public List<Data> getGroups() { return groups; }
public void setTitle(String title) { this.title = title; }
public void setId(Long id) { this.id = id; }
public void setChildren(Boolean children) { this.children = children; }
public void setGroups(List<Data> groups) { this.groups = groups; }
public String toString() {
return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
}
}
相当简单,不是吗?只要有一个合适的JavaBean并调用Gson#fromJson()
。
另请参阅: