我有这两节课:
Foo.java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Foo {
private ListWrapper data;
}
ListWrapper.java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ListWrapper {
@JsonValue
private List<String> value;
}
我正在使用以下方法测试序列化:
public void testSerialization() throws JsonProcessingException {
Foo foo = new Foo();
foo.setData(new ListWrapper(new ArrayList<String>() {
{
add("foo");
add("bar");
}
}));
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(foo));
}
输出为{"data":["foo","bar"]}
。现在,我尝试使用以下方法反序列化此json字符串:
public void testDeserialization() throws IOException {
String json = "{\"data\":[\"foo\",\"bar\"]}";
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.readValue(json, Foo.class));
}
但这不起作用。我收到以下异常:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `ListWrapper` out of START_ARRAY token
at [Source: (String)"{"data":["foo","bar"]}"; line: 1, column: 9] (through reference chain: Foo["data"])
我不知道为什么会这样。谁能给我一个提示?我正在使用Jackson 2.9.9。
答案 0 :(得分:1)
Jackson对象映射器引发了异常,因为它期望Object
属性的类型为data
,但是找到了Array
。
@JsonValue
批注用于编组。解组的类似注释为@JsonCreator
。
注释您的ListWrapper
构造函数
@JsonCreator
public ListWrapper(List<String> value) {
this.value = value;
}