Deserialzing JSON with multiple types for a property

佐手、 提交于 2019-12-14 03:57:03

问题


I am working with a 3rd party API that returns three different types for the same JSON property, depending one how many nested objects it contains. I'm trying to figure out the best way to handle deserializing these objects using Jackson (preferably with Retrofit).

A simplified example: when retrieving a Customer record from this API, the response might be any one of:

  1. Customer has multiple phone numbers; returns an array of PhoneObjects

    {
        "Phones": {
            "PhoneObject":[
                {"number":"800 555 6666","type":"Home"},
                {"number":"800 555 4444","type":"Work"}
            ]
        }
    }
    
  2. Customer has one phone number; return a single PhoneObject

    {
        "Phones": {
            "PhoneObject": {"number":"800 555 6666","type":"Home"}
        },
    }
    
  3. Customer has no phone numbers; return an empty string(!)

    {
        "Phones": {
            "PhoneObject":""
        }
    }
    

Currently, I handle this by deserializing with Jackson into a Map<String, Object> and inspecting the Object to determine what type it is, and then inserting it into, e.g. a List<PhoneObject> (returning an empty List if the object is not present). However this is cumbersome and would like to find a cleaner way to deserialize these objects.


回答1:


I was able to parse all 3 JSON strings into this Phones class

class Phones {
    @JsonProperty("PhoneObject")
    private List<PhoneObject> phoneObjects;
}

with this ObjectMapper configuration:

ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

ACCEPT_SINGLE_VALUE_AS_ARRAY allows parsing a value into a list with size 1.

ACCEPT_EMPTY_STRING_AS_NULL_OBJECT allows parsing an empty string as a null. In this case phoneObjects ends up being null. Not ideal but I don't know of an easy way to get an empty list here.

You may or may not need UNWRAP_ROOT_VALUE depending on your POJOs.



来源:https://stackoverflow.com/questions/44527192/deserialzing-json-with-multiple-types-for-a-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!