为属性反序列化具有多种类型的JSON [英] Deserialzing JSON with multiple types for a property

查看:118
本文介绍了为属性反序列化具有多种类型的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个第三方API,该API针对相同的JSON属性返回三种不同的类型,具体取决于其中包含多少个嵌套对象.我正在尝试找出使用Jackson进行反序列化这些对象的最佳方法(最好是使用Retrofit).

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).

一个简化的示例:从此API检索客户记录时,响应可能是以下任何一项:

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

  1. 客户有多个电话号码;返回PhoneObjects

{
    "Phones": {
        "PhoneObject":[
            {"number":"800 555 6666","type":"Home"},
            {"number":"800 555 4444","type":"Work"}
        ]
    }
}

  • 客户有一个电话号码;返回一个PhoneObject

    {
        "Phones": {
            "PhoneObject": {"number":"800 555 6666","type":"Home"}
        },
    }
    

  • 客户没有电话号码;返回一个空字符串(!)

  • Customer has no phone numbers; return an empty string(!)

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

  • 当前,我通过用Jackson将反序列化为Map<String, Object>并检查Object以确定其类型,然后将其插入例如List<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.

    推荐答案

    我能够将所有3个JSON字符串解析为该Phones

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

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

    使用此ObjectMapper配置:

    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 允许将值解析为大小为1的列表.

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

    ACCEPT_EMPTY_STRJ 允许将空字符串解析为null.在这种情况下,phoneObjects最终为null.不理想,但我不知道在这里获得空列表的简便方法.

    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.

    这篇关于为属性反序列化具有多种类型的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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