使用Jackson将带有私有列表属性的JSON数组反序列化为对象 [英] Deserialize JSON Array to Object with private list property using Jackson
本文介绍了使用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]
这篇关于使用Jackson将带有私有列表属性的JSON数组反序列化为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文