0

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.

cesarsotovalero
  • 1,116
  • 6
  • 15
  • Check that the file contains an actual JSON array of Person. It seems like it may contain a single JSON person object – tucuxi Dec 09 '20 at 10:49
  • At the top level you have `JSON Object`. Try to deserialise it like this: `objectMapper.readValue(jsonString, Person.class)` – Michał Ziober Dec 09 '20 at 12:40

1 Answers1

2

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

Stian
  • 58
  • 1
  • 5