让Jackson将单个JSON对象解释为具有一个元素的数组 [英] Make Jackson interpret single JSON object as array with one element

查看:470
本文介绍了让Jackson将单个JSON对象解释为具有一个元素的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to make Jackson interpret single JSON object as an array with one element and vice versa?

示例,我有两种略有不同的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本身。杰克逊是否有一些配置我可以篡改以使其接受 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>>() {
        });
System.out.println(points);

这篇关于让Jackson将单个JSON对象解释为具有一个元素的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆