简体   繁体   English

Jackson 用空字符串代替 object 反序列化 JSON 字符串

[英]Jackson deserialize JSON string with empty string instead of object

I'm having trouble deserializing a response I receive from an external api.我在反序列化从外部 api 收到的响应时遇到问题。

Normally the API returns the following JSON:通常 API 返回以下 JSON:

{ 
 "RootObj": {
   "InnerObj" : [
           {"Elem1": "Val1"},
       ]
    }
}

That is parsed all fine.解析得很好。 However when the API does not find something it returns this JSON:然而,当 API 没有找到它时,它会返回这个 JSON:

{ 
 "RootObj": ""
}

But with that JSON, Jackson cannot deserialize it.. neither can it when you use the deserializeOption ACCEPT_EMPTY_STRING_AS_NULL_OBJECT.但是有了 JSON,Jackson 就不能反序列化它了。当你使用反序列化选项 ACCEPT_EMPTY_STRING_AS_NULL_OBJECT 时也不能。

The JSON does get converted to: JSON 确实转换为:

{ 
 "RootObj": null
}

However, now Jackson cannot instantiate my POJO because of the null pointer.但是,由于 null 指针,现在 Jackson 无法实例化我的 POJO。 I expected it to create the rootObj class, with the InnerObj set to null..我希望它能够创建 rootObj class,并将 InnerObj 设置为 null..

I've tried all sorts of tactics, like @jsonsetter etc. But I had no luck in doing so.我尝试了各种策略,比如@jsonsetter 等。但我没有运气。 Does anyone have an idea how to solve this?有谁知道如何解决这个问题? Preferably with an objectmapper setting.最好使用对象映射器设置。

Add this property to ObjectMapper将此属性添加到ObjectMapper

DeserializationFeature ACCEPT_EMPTY_STRING_AS_NULL_OBJECT

Feature that can be enabled to allow JSON empty String value ("") to be bound to POJOs as null.可以启用以允许 JSON 空字符串值 ("") 作为 null 绑定到 POJO 的功能。 If disabled, standard POJOs can only be bound from JSON null or JSON Object (standard meaning that no custom deserializers or constructors are defined; both of which can add support for other kinds of JSON values); If disabled, standard POJOs can only be bound from JSON null or JSON Object (standard meaning that no custom deserializers or constructors are defined; both of which can add support for other kinds of JSON values); if enabled, empty JSON String can be taken to be equivalent of JSON null.如果启用,则可以将空 JSON 字符串视为等效于 JSON null。

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

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