杰克逊反序列化问题与数组和对象 [英] Jackson deserialization issues with arrays and objects
问题描述
我遇到了一个问题,我的JSON响应可以是对象或对象数组
I'm running into a problem where my JSON response can be object or an array of objects
单个值的Foobar示例:
Foobar example with a single value:
{
"foo": {"msg": "Hello World" }
}
带数组的Foobar示例:
Foobar example with an array:
{
"foo": [
{ "msg": "Hello World" },
{ "msg": "Goodbye World" }
]
}
我希望强制单值进入任何数组但到目前为止,我发现转换所有数据的唯一方法单个值作为数组。
I want the force the single value into any array but so far, the only way I found converted all single values as arrays.
ACCEPT_SINGLE_VALUE_AS_ARRAY
ACCEPT_SINGLE_VALUE_AS_ARRAY
http://wiki.fasterxml.com/JacksonFeaturesDeserialization
我一直在寻找一个对单个属性做同样事情的注释,但到目前为止谷歌还没有找到任何例子。
I've been looking around for an annotation that does the same thing for a single property but so far google hasn't turned up any examples.
之前有没有人遇到过这个问题,我真的不想把所有东西重写为数组,以使RestTemplate与一个有缺陷的服务一起工作。
Has anyone run into this problem before, I really don't want to rewrite everything as arrays to make RestTemplate work with a buggy service.
推荐答案
我希望强制将单个值放入任何数组,但到目前为止,我找到的唯一
方式将所有单个值转换为数组。
这不应该是这种情况。对于给定的ObjectMapper, ACCEPT_SINGLE_VALUE_AS_ARRAY
属性 是 打开/关闭,但其行为完全由目标属性管理正在映射JSON值。
This simply shouldn't be the case. The ACCEPT_SINGLE_VALUE_AS_ARRAY
property is on/off for a given ObjectMapper, but its behavior is entirely governed by the target property the JSON value is being mapped to.
- 当ACCEPT_SINGLE_VALUE_AS_ARRAY打开时,将JSON值映射到Java集合属性不会导致错误。
- 当ACCEPT_SINGLE_VALUE_AS_ARRAY打开时,将JSON值映射到Java基本属性(也)不会导致错误。
以下代码说明:
class Foo {
private String msg;
// Constructor, setters, getters
}
class Holder {
private List<Foo> foo;
private Foo other;
// Constructors, setters, getters
}
public class FooTest {
@org.junit.Test
public void testCollectionFromJSONValue() throws Exception {
final InputStream stream = Thread.currentThread()
.getContextClassLoader().getResourceAsStream("foo.json");
final String json = IOUtils.toString(stream);
final ObjectMapper mapper = new ObjectMapper();
mapper.configure(
DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY,
true);
final Holder holder = mapper.readValue(json, Holder.class);
System.out.println(holder);
}
}
这取决于以下JSON:
Which relies on the following JSON:
{
"foo": {
"msg": "Hello World"
},
"other": {
"msg": "Goodbye"
}
}
运行代码将显示foo属性已成功反序列化为列表,而other属性被反序列化为(基本)Foo类型。
Running the code will show that the "foo" property is successfully deserialized into a list, whereas the "other" property gets deserialized into a (basic) Foo type.
这篇关于杰克逊反序列化问题与数组和对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!