让Jackson将单个JSON对象解释为具有一个元素的数组

Xia*_* Yu 40 java json jackson

有没有办法让杰克逊将单个JSON对象解释为具有一个元素的数组,反之亦然?

例如,我有2种略有不同的JSON格式,我需要两者都映射到同一个Java对象:

格式A(带有一个元素的JSON数组):

points : [ {
    date : 2013-05-11
    value : 123
}]
Run Code Online (Sandbox Code Playgroud)

格式B(JSON对象,是的,我知道它看起来"错误",但它是我给的):

points : {
    date : 2013-05-11
    value : 123
}
Run Code Online (Sandbox Code Playgroud)

目标Java对象,以上两者都应转换为:

//Data.java 
public List<Point> points;
//other members omitted

//Point.java
class Point {
    public String date;
    public int value;
}
Run Code Online (Sandbox Code Playgroud)

目前,只有A才能正确解析数据.我想避免直接篡改JSON本身.杰克逊是否有一些配置我可以篡改以使其接受B

Mic*_*ber 67

尝试DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY- 它应该适合你.

例:

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>>() {});
Run Code Online (Sandbox Code Playgroud)

  • 也可以使用 @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY) 在每个字段的基础上启用它 (3认同)

phi*_*rse 8

Jackson 1.x兼容版本使用DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY.所以上面的答案改为:

final String json = "{\"date\" : \"2013-05-11\",\"value\" : 123}";

final ObjectMapper mapper = new ObjectMapper()
    .enable(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
final List<Point> points = mapper.readValue(json,
    new TypeReference<List<Point>>() {
    });
System.out.println(points);
Run Code Online (Sandbox Code Playgroud)