简体   繁体   中英

How to serialize a JSON file with tree structure with Jackson

I need to serialize a JSON file to a Java object. The JSON file has a tree structure, which means that the object at the root has children that are instances of itself and so on. For example, consider the following JSON file:

{
  "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": []
    }
  ]
}

I have tried the serialization using the Jackson library. This is the object I want to serialize to:

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
}

This is what I have tried so far:

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

However, It triggers the following MismatchedInputException: Cannot deserialize instance of java.util.ArrayList<Person> out of START_OBJECT token .

Cannot deserialize instance of java.util.ArrayList out of START_OBJECT token. Because your json file is a Person object and not a List object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM