Dan*_*Dan 1 java spring jackson
我遇到了一个问题,我的JSON响应可以是对象或对象数组
具有单个值的Foobar示例:
{
"foo": {"msg": "Hello World" }
}
Run Code Online (Sandbox Code Playgroud)
带阵列的Foobar示例:
{
"foo": [
{ "msg": "Hello World" },
{ "msg": "Goodbye World" }
]
}
Run Code Online (Sandbox Code Playgroud)
我希望强制将单个值放入任何数组但到目前为止,我发现将所有单个值转换为数组的唯一方法.
ACCEPT_SINGLE_VALUE_AS_ARRAY
http://wiki.fasterxml.com/JacksonFeaturesDeserialization
我一直在寻找一个针对单个属性做同样事情的注释,但到目前为止谷歌还没有发现任何例子.
有没有人遇到过这个问题,我真的不想把所有东西重写为数组,以使RestTemplate与一个有缺陷的服务一起工作.
我希望强制将单个值放入任何数组但到目前为止,我发现将所有单个值转换为数组的唯一方法.
这根本不应该是这种情况.对于给定的ObjectMapper,该ACCEPT_SINGLE_VALUE_AS_ARRAY属性是打开/关闭的,但其行为完全由JSON值映射到的目标属性控制.
由以下代码说明:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
它依赖于以下JSON:
{
"foo": {
"msg": "Hello World"
},
"other": {
"msg": "Goodbye"
}
}
Run Code Online (Sandbox Code Playgroud)
运行代码将显示"foo"属性已成功反序列化为列表,而"other"属性被反序列化为(基本)Foo类型.
| 归档时间: |
|
| 查看次数: |
5685 次 |
| 最近记录: |