1

Hello I am stuck in converting JSON NESTED Array to JAVA Objects using GSON labirary.

Here is my JSON String

[{\"name\":\"3214657890RootSAPSSE\",\"children\":[{\"name\":\"672BENIAMEEN .Sales Base Market SectionCustomer Representative\"},{\"name\":\"672BENIAMEEN .Sales Base Market SectionPeão\"}]}] 

I tested my code with x="[{\"name\":\"MyNode\"}]"; and for this my java code is

Gson gson = new Gson(); 
java.lang.reflect.Type type = new TypeToken<List<EmployeeJSONObj>>(){}.getType();
List<EmployeeJSONObj>l = gson.fromJson(x, type);
System.out.println("hello "+l.get(0).getName());

AND EmployeeJSONObj is class

public class EmployeeJSONObj {
    private String name;
    EmployeeJSONObj()
    {

    }
    public String getName()
    {
        return name;
    }

}

This is working fine. But my this code gives me error when I change the JSON String to

[{\"name\":\"3214657890RootSAPSSE\",\"children\":[{\"name\":\"672BENIAMEEN .Sales Base Market SectionCustomer Representative\"},{\"name\":\"672BENIAMEEN .Sales Base Market SectionPeão\"}]}] 

This is a tree. I want generic solution, which can traverse the whole nested json string. I'm stuck in the middle of a project. Please help me to solve this.

Thanks

4

1 回答 1

1

您的班级需要一个List孩子,以便 Gson 可以反序列化children数组。这是一个工作示例。

public static void main(String args[]) {
    String str = "[{\"name\":\"3214657890RootSAPSSE\",\"children\":[{\"name\":\"672BENIAMEEN .Sales Base Market SectionCustomer Representative\"},{\"name\":\"672BENIAMEEN .Sales Base Market SectionPeão\"}]}]";
    System.out.println(str);

    Gson gson = new Gson(); 
    java.lang.reflect.Type type = new TypeToken<List<EmployeeJSONObj>>(){}.getType();
    List<EmployeeJSONObj>l = gson.fromJson(str, type);
    System.out.println(l);
}
public static  class EmployeeJSONObj {
    private String name;
    private List<EmployeeJSONObj> children = new LinkedList<>();
    EmployeeJSONObj()
    {

    }
    public String getName()
    {
        return name;
    }

    public String toString() {
        return "name: " + name + ", children = " + children;
    }

}

印刷

[{"name":"3214657890RootSAPSSE","children":[{"name":"672BENIAMEEN .Sales Base Market SectionCustomer Representative"},{"name":"672BENIAMEEN .Sales Base Market SectionPeão"}]}]
[name: 3214657890RootSAPSSE, children = [name: 672BENIAMEEN .Sales Base Market SectionCustomer Representative, children = [], name: 672BENIAMEEN .Sales Base Market SectionPeão, children = []]]
于 2013-09-20T12:52:16.523 回答