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