使用Jackson将带有私有列表属性的JSON数组反序列化为对象
问题描述:
JSON字符串,例如:
A JSON string like:
[
"a", "b", "c"
]
通常将反序列化为List<String>
.但是我有一个看起来像这样的课:
Would usually be deserialized to List<String>
. But I have a class that looks like this:
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
的对象,如:
Now I want to deserialize the above JSON string into an object of class Foo
like:
Foo foo = new ObjectMapper().readValue(jsonString, Foo.class);
那怎么可能?
我已经尝试将@JsonCreator
与构造函数一起使用,但总是得到:
I've already tried to use @JsonCreator
with the constructor but always get:
JsonMappingException: Can not deserialize instance of ... out of START_ARRAY token
答
对于Jackson 2.4.3,此
With Jackson 2.4.3, this
@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]