使用嵌套对象列表反序列化 json

我想使用 jackson-databind 将一个 json 反序列化为一个包含其他对象列表的对象。


我正在尝试在 json 下反序列化。我有 Class class1,它有一个List<NestedProp>. Prop2 是一个数组列表。List<NestedProp> prop2.


结构类`


class Class1 {

  String prop1;

  List<NestedProp> prop2;

  //setters getters

}


class NestedProp {

  String p1;

  String p2;

  //setters getters

}

`


```

  "class1": {

    "prop1": "pp",

    "prop2": [

      {

        "nestedProp": [

          {

            "p1": "127",

            "p2": "1"

          },

          {

            "p1": "128",

            "p2": "2"

          }

        ]

      }

    ]

  }


While deserialisingI get the below exception:


>com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `NestedProp` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('127')

 at [Source: (File); line: 59, column: 7] (through reference chain: java.util.ArrayList[1]->Class1["prop2"]->java.util.ArrayList[0])



    List<Class1> testData = objectMapper.readValue(test.json, Class1.class);


子衿沉夜
浏览 143回答 1
1回答

蝴蝶不菲

您的JSON有效负载中有两个数组。所以,你需要POJO为它创建额外的。请参阅以下示例:import com.fasterxml.jackson.databind.ObjectMapper;import java.io.File;import java.util.List;public class JsonApp {&nbsp; &nbsp; public static void main(String[] args) throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; File jsonFile = new File("./resource/test.json").getAbsoluteFile();&nbsp; &nbsp; &nbsp; &nbsp; ObjectMapper mapper = new ObjectMapper();&nbsp; &nbsp; &nbsp; &nbsp; Root root = mapper.readValue(jsonFile, Root.class);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(root);&nbsp; &nbsp; }}class Root {&nbsp; &nbsp; private Class1 class1;&nbsp; &nbsp; //getters, setters, toString}class Class1 {&nbsp; &nbsp; private String prop1;&nbsp; &nbsp; private List<NestedProps> prop2;&nbsp; &nbsp; //getters, setters, toString}class NestedProps {&nbsp; &nbsp; private List<NestedProp> nestedProp;&nbsp; &nbsp; //getters, setters, toString}class NestedProp {&nbsp; &nbsp; private String p1;&nbsp; &nbsp; private String p2;&nbsp; &nbsp; //getters, setters, toString}对于以下JSON:{&nbsp; "class1": {&nbsp; &nbsp; "prop1": "pp",&nbsp; &nbsp; "prop2": [&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "nestedProp": [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "p1": "127",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "p2": "1"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "p1": "128",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "p2": "2"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; ]&nbsp; }}以上示例打印:Root{class1=Class1{prop1='pp', prop2=[NestedProps{nestedProp=[NestedProp{p1='127', p2='1'}, NestedProp{p1='128', p2='2'}]}]}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java