我有以下两个班级:
@JsonIgnoreProperties(ignoreUnknown = true)
public class ChangesJSON {
@JsonProperty("changes")
List<ChangeJSON> changes;
@JsonProperty("more")
Boolean more;
}
public class ChangeJSON {
@JsonProperty("epoch")
Long epoch;
@JsonProperty("payload")
Map<String, Object> payload;
}
当我尝试使用此测试进行反序列化时:
String test = "{\"changes\":[{\"epoch\":1441556306522,\"payload\":\"{\"to\":1}\"},{\"epoch\":1441555481524,\"payload\":\"{\"to\":-1}\"}],\"more\":false}";
@Test
public void myTest() {
ObjectMapper mapper = new ObjectMapper();
ChangesJSON result = null;
try {
result = mapper.readValue(test, ChangesJSON.class);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
assertNotNull(result);
}
我得到以下异常:
com.fasterxml.jackson.databind.JsonMappingException:不能 从String值实例化java.util.LinkedHashMap类型的值 ( '{'); [来源:没有单字符串构造函数/工厂方法 { “变化”:[{ “历元”:1441556306522, “有效载荷”: “{” 到 “:1}”},{ “历元”:1441555481524, “有效载荷”: “{” 到 “: - 1}”} ], “多”:假}; line:1,column:35](通过参考链: demo.ChangesJSON [ “变化”] - &GT; java.util.ArrayList中[0] - &GT; demo.ChangeJSON [ “有效载荷”])
地图似乎存在问题,但我认为杰克逊应该能够处理地图。当我将地图更改为Map时,我也遇到了同样的问题。但我确实需要支持各种类作为地图的值。
答案 0 :(得分:6)
您在payload
对象周围有引号。尝试更改此部分:
\"payload\":\"{\"to\":1}\"
进入这个:
\"payload\":{\"to\":1}
答案 1 :(得分:1)
我认为JSON本身存在问题。它无视:
{"changes":[{"epoch":1441556306522,"payload":"{"to":1}"},{"epoch":1441555481524,"payload":"{"to":-1}"}],"more":false}
应该是这样的:
{"changes":[{"epoch":1441556306522,"payload":{"to":1}},{"epoch":1441555481524,"payload":{"to":-1}}],"more":false}
所以:
String test = "{\"changes\":[{\"epoch\":1441556306522,\"payload\":{\"to\":1}},{\"epoch\":1441555481524,\"payload\":{\"to\":-1}}],\"more\":false}";