使用子项

时间:2018-04-30 09:33:50

标签: java json jackson

我有一个使用带子项的对象的Json列表

{
 "id":"154",
 "name":"peter",
 "children": [
               {
                "id":"122",
                "name": "mick",
                "children":[]
               },
               {
                "id":"123",
                "name": "mick",
                "children":[]
               }
            ]
}

这是我的对象的类:

public class person{
                    private String id;
                    private String name;
                    private List<person> children;

//getters and setters
}

当我尝试反序列化此对象时,出现以下错误

  

无法从START_ARRAY令牌中反序列化人员实例

我该怎么办?

4 个答案:

答案 0 :(得分:1)

JSON包含一系列人员。 您的班级是person

的列表

更改建议的@Naveed Yadav之类的JSON或将类更改为

public class Person{
             private String id;
             private String name;
             private Person[] children;

//getters and setters
}

(BTW类名应该是Java中的大写)

答案 1 :(得分:1)

修复JSON正文中的语法错误,您将处于良好的状态:

{
 "id":"154",
 "name":"peter",
 "children": [
               {
                "id":"122",
                "name": "mick",
                "children":[], <== Excess comma
               } <== Missing comma 
               {
                "id":"123",
                "name": "mick",
                "children":[], <== Excess comma
               }
            ]
}

有效的一个:

{
    "id": "154",
    "name": "peter",
    "children": [{
            "id": "122",
            "name": "mick",
            "children": []
        },
        {
            "id": "123",
            "name": "mick",
            "children": []
        }
    ]
}

答案 2 :(得分:0)

您需要更改您的POJO声明,如下所示: -

 public class person{
                private String id;
                private String name;
                private List<Children> children;

               //getters and setters

   private class Children{
                private String id;
                private String name;
                private String[] children;

}

答案 3 :(得分:-1)

{
 "id":"154",
 "name":"peter",
 "children": 
               {
                "id":"122",
                "name": "mick",
                "children":[],
               }
               {
                "id":"123",
                "name": "mick",
                "children":[],
               }

}