如何用jackson序列化具有树结构的json文件

flvlnr44  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(440)

我需要将json文件序列化为java对象。json文件有一个树结构,这意味着根对象有自己的子对象,以此类推。例如,考虑以下json文件:

{
  "name": "peter",
  "parent": null,
  "children": [
    {
      "name": "simon",
      "parent": "peter",
      "children": [
        {
          "name": "john",
          "parent": "simon",
          "children": []
        }
      ]
    },
    {
      "name": "javier",
      "parent": "peter",
      "children": []
    },
    {
      "name": "martin",
      "parent": "peter",
      "children": []
    }
  ]
}

我试过使用jackson库进行序列化。这是我要序列化到的对象:

public class Person {

   private String name;
   private Person parent;
   private List<Person> children;

   @JsonCreator
   public Project(@JsonProperty("name") String name,
                  @JsonProperty("parent") Person parent,
                  @JsonProperty("children") List<Person> children) {
      this.name = name;
      this.coordinates = parent;
      this.children = children;
   }

   // getters, setters, and constructor
}

这就是我迄今为止所尝试的:

String jsonString = Files.readString(Paths.get("/path_to/file.json"));
List<Person> listModel = objectMapper.readValue(jsonString, new TypeReference<>() {});

但是,它会触发以下事件 MismatchedInputException: Cannot deserialize instance of java.util.ArrayList<Person> out of START_OBJECT token .

ua4mk5z4

ua4mk5z41#

无法反序列化java.util.arraylist示例的起始\u对象标记。因为json文件是person对象而不是list对象

相关问题