以下のようなJavaオブジェクトがあります。Jackson jsonでシリアル化/逆シリアル化する方法は?
public class Employee {
private String name;
List<Employee> friends;
}
JSON:
{"friends":[{"name":"abc"}],[{{"name":"pqr"}}]}
私の実装クラス:
public class EmployeeImpl implements Employee, Serializable {
private String name;
private List<Employee> friends;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public List<Employee> getFriends() { return friends; }
public void setFriends(List<Employee> friends) { this.friends = friends; }
}
テスト クラス:
public class Test {
public static void main(String[] args) throws Exception {
String json = "{\"name\":\"gangi\", \"friends\":[{\"name\":\"abc\"},{\"name\":\"pqr\"}]}";
Employee employee = deserializeJson(json, new TypeReference<EmployeeImpl>(){});
}
public static <T> T deserializeJson(String jsonData, TypeReference<T> typeRef) throws Exception {
ObjectMapper mapper = new ObjectMapper();
return mapper.<T>readValue(jsonData, typeRef);
}
}
例外スタックトレース...
Exception in thread "main" org.codehaus.jackson.map.JsonMappingException:
Can not construct instance of Employee,
problem: abstract types can only be instantiated with additional type information at
[Source: java.io.StringReader@68da4b71; line: 1, column: 29]
(through reference chain: EmployeeImpl["friends"]) at
org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)