简体   繁体   English

Jackson JSON反序列化列表

[英]Jackson JSON Deserialization List

I want to deserialize a JSON string using the same POJO for two kind of messages. 我想对两种消息使用相同的POJO反序列化JSON string Take a look at the message below 看看下面的消息

{
"success": true,
"data": [
    {
        "id": 2,
        "comments": null
    },
    {
        "id": 3,
        "comments": null
    }
]
}

The data is an array , but sometimes the data is a single object: 数据是数组 ,但有时数据是单个对象:

{
"success": true,
"data":
    {
        "id": 2,
        "comments": null
    }
}

My POJO looks like this: 我的POJO看起来像这样:

public void setData(List<Object> data)
{
    this.data = data;
}

Is there any way to deserialize the second message (where data is not an array) using the same class? 有没有办法使用相同的类反序列化第二条消息(数据不是数组)?

Kind regards, Ricardo 亲切的问候,里卡多

I havent used it, but there is a deserialization feature that allows for this on deserialization: 我还没有使用过它,但是有一个反序列化功能可以在反序列化上实现:

ACCEPT_SINGLE_VALUE_AS_ARRAY (default: false) ACCEPT_SINGLE_VALUE_AS_ARRAY(默认值:false)

Allows auto-conversion from non-JSON-array values to single-element arrays and Collections (adding implicit "array wrapper"): this is sometimes necessary for interoperability, as some libraries and frameworks omit JSON arrays when serializing single-element arrays. 允许从非JSON数组值自动转换为单元素数组和集合(添加隐式“数组包装器”):有时对于互操作性是必要的,因为某些库和框架在序列化单元素数组时会省略JSON数组。

also looks like there is the opposite for serialization as well (writing single element arrays to non-JSON array 看起来也有相反的序列化(将单个元素数组写入非JSON数组

UNWRAP_SINGLE_VALUE_ARRAYS (default: false) (since 2.4) UNWRAP_SINGLE_VALUE_ARRAYS(默认值:false)(从2.4开始)

Allows auto-conversion from single-element arrays to non-JSON-array values : this is similar to the ACCEPT_SINGLE_VALUE_AS_ARRAY feature but works in the opposite manner (ie if you have a bound property that is not an array or collection, a single value array in JSON would be acceptable to bind to that property). 允许从单元素数组自动转换为非JSON数组值:这类似于ACCEPT_SINGLE_VALUE_AS_ARRAY功能,但工作方式相反(即,如果绑定属性不是数组或集合,则为单个值数组) JSON绑定到该属性是可以接受的)。 If the JSON value contains more than one element in the array, deserialization will still fail. 如果JSON值在数组中包含多个元素,则反序列化仍将失败。

see https://github.com/FasterXML/jackson-databind/wiki/Deserialization-Features 参见https://github.com/FasterXML/jackson-databind/wiki/Deserialization-Features

I am unsure if there is a way to do this for specific fields. 我不确定是否可以针对特定领域执行此操作。 Seems to be an all-or-nothing kind of thing. 似乎是全有或全无的事情。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM