JSON字符串,如:
[
"a", "b", "c"
]
通常会反序列化为List<String>
。但我有一个看起来像这样的课程:
public class Foo {
private List<String> theList;
public Foo(List<String> theList) {
this.theList = theList;
}
public String toString() {
return new ObjectMapper().writeValueAsString(theList);
}
// ... more methods
}
现在我想将上面的JSON字符串反序列化为类Foo
的对象,如:
Foo foo = new ObjectMapper().readValue(jsonString, Foo.class);
这怎么可能?
我已经尝试将@JsonCreator
与构造函数一起使用,但总是得到:
JsonMappingException: Can not deserialize instance of ... out of START_ARRAY token
答案 0 :(得分:3)
使用Jackson 2.4.3,这个
@JsonCreator
public Foo(List<String> theList) {
this.theList = theList;
}
...
String jsonString = "[\"a\", \"b\", \"c\"]";
Foo foo = new ObjectMapper().readValue(jsonString, Foo.class);
System.out.println(foo.getTheList());
适合我。它打印
[a, b, c]