Google의 Gson을 잠재적 인 JSON 플러그인으로 보았습니다. 누구나이 JSON 문자열에서 Java를 생성하는 방법에 대한 지침을 제공 할 수 있습니까?
Google Gson 은 제네릭 및 중첩 된 Bean을 지원합니다. []JSON의 배열을 나타내며 같은 자바 컬렉션에 매핑해야합니다 List아니면 그냥 일반 자바 배열입니다. {}JSON에서 객체를 나타내며 자바에 매핑해야 Map하거나 일부 자바 빈즈 클래스입니다.
여러 속성을 가진 JSON 객체가 있으며이 속성은 groups동일한 유형의 중첩 객체 배열을 나타냅니다. 이것은 Gson으로 다음과 같은 방식으로 구문 분석 할 수 있습니다.
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().
또한보십시오: