简体   繁体   中英

Jackson deserialize JSON string with empty string instead of object

I'm having trouble deserializing a response I receive from an external api.

Normally the API returns the following JSON:

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

That is parsed all fine. However when the API does not find something it returns this JSON:

{ 
 "RootObj": ""
}

But with that JSON, Jackson cannot deserialize it.. neither can it when you use the deserializeOption ACCEPT_EMPTY_STRING_AS_NULL_OBJECT.

The JSON does get converted to:

{ 
 "RootObj": null
}

However, now Jackson cannot instantiate my POJO because of the null pointer. I expected it to create the rootObj class, with the InnerObj set to null..

I've tried all sorts of tactics, like @jsonsetter etc. But I had no luck in doing so. Does anyone have an idea how to solve this? Preferably with an objectmapper setting.

Add this property to 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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