让 Jackson 将单个 JSON 对象解释为具有一个元素的数组 [英] Make Jackson interpret single JSON object as array with one element
问题描述
有没有办法让 Jackson 将单个 JSON 对象解释为一个包含一个元素的数组,反之亦然?
Is there a way to make Jackson interpret single JSON object as an array with one element and vice versa?
例如,我有 2 种略有不同的 JSON 格式,我需要将它们都映射到同一个 Java 对象:
Example, I have 2 slightly different formats of JSON, I need both to map to same Java object:
格式A(一个元素的JSON数组):
Format A (JSON array with one element):
points : [ {
date : 2013-05-11
value : 123
}]
格式 B(JSON 对象,是的,我知道它看起来错误",但这是我得到的):
Format B (JSON object, yes I know it looks "wrong" but it's what I'm given):
points : {
date : 2013-05-11
value : 123
}
以上两者都应转换为的目标 Java 对象:
Target Java object that both of the above should convert to:
//Data.java
public List<Point> points;
//other members omitted
//Point.java
class Point {
public String date;
public int value;
}
目前,只有 A 会正确解析为数据.我想避免直接篡改 JSON 本身.Jackson 中是否有一些我可以篡改的配置以使其接受 B ?
Currently, only A will parse properly to Data. I want avoid directly tampering with the JSON itself. Is there some configuration in Jackson I can tamper with in order to make it accept B ?
推荐答案
尝试使用 DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY
- 它应该适合你.
Try with DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY
- it should work for you.
示例:
final String json = "{"date" : "2013-05-11","value" : 123}";
final ObjectMapper mapper = new ObjectMapper()
.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
final List<Point> points = mapper.readValue(json,
new TypeReference<List<Point>>() {});
这篇关于让 Jackson 将单个 JSON 对象解释为具有一个元素的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!