如何序列化/反序列化以下对象?

时间:2012-07-22 16:19:48

标签: json jackson

我有一个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‌​)

2 个答案:

答案 0 :(得分:3)

将以下注释添加到您的Employee界面

`@JsonDeserialize(as=EmployeeImpl.class)`

答案 1 :(得分:0)

您的json格式不正确。有关如何在json中定义数组/列表,请参见[http://www.json.org/]。 json构建示例[http://java.dzone.com/tips/json-processing-using-jackson]