无法解析在响应中作为START_OBJECT或START_ARRAY返回的对象

时间:2016-01-12 07:18:11

标签: java jaxb jackson jaxb2 jersey-client

在Expedia Affiliate Network的一个API中,下面部分响应将作为数组返回,而其他对象则为

"Surcharges": {
       "Surcharge": {
                "_type": "TaxAndServiceFee",
                "_amount": "11.94"
        },
        "_size": "1"
}

"Surcharges": {
       "Surcharge": [
            {
                    "_type": "TaxAndServiceFee",
                    "_amount": "11.94"
            },
            {
                    "_type": "Somethingelse",
                    "_amount": "11.94"
            }
        ],
        "_size": "1"
}

相应的JAXB模型是

@JsonPropertyOrder({
    "@size",
    "Surcharge"
})
@JsonIgnoreProperties(ignoreUnknown = true)
public class Surcharges {

    @JsonProperty("@size")
    private String Size;
    @JsonProperty("Surcharge")
    private Surcharge[] Surcharge;
    //was not part of the original model, added hoping this might solve :(
    @JsonProperty("Surcharge")
    private Surcharge Surcharge1;

    .....
}

解析失败,

com.sun.jersey.api.client.ClientHandlerException: org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of in.xxx.xxxxx.port.adapter.expedia.hotels.list.response.Surcharge out of START_ARRAY token

并将Surcharge更改为数组将导致

com.sun.jersey.api.client.ClientHandlerException: org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of in.xxx.xxxxxx.port.adapter.expedia.hotels.list.response.Surcharge out of START_OBJECT token

处理此响应的最佳方法是什么

我可以在Jackson Feature配置中找到解决方案

ACCEPT_SINGLE_VALUE_AS_ARRAY,如何使用Jersey的ClientConfig进行设置?

1 个答案:

答案 0 :(得分:0)

已解决使用客户端配置JacksonJaxbProvider

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

JacksonJaxbJsonProvider jacksonProvider = new JacksonJaxbJsonProvider();
jacksonProvider.setMapper(mapper);
config.getSingletons().add(jacksonProvider);