我正在尝试调用REST端点,该端点为经过验证的城市地址返回JSON。在一次成功的通话中,我得到了这样的话:
{
"success":true,
"results":[
{
"civicnumberid":123456,
"civic_address_as_string":"123 Main Street, My City, My Municipality, My County",
"esri_point":{
"x":12345.678,
"y":54321.012
}
}
],
"error":null
}
但是,如果我以服务无法处理的格式发送请求,我会退回这样的内容:
{
"success":false,
"results":null,
"error":{
"code":123,
"message":"Invalid Civic Address. Valid Example: 123 Main St, My City...",
"details":[
"The civic address submitted to the service contained an alphabetic character where a number was expected."
]
}
}
请注意 “results”:null 。尝试使用JAX-RS 2.0和Jackson 2.5.1转换响应时:
ResponseObject response = client.target(url)
.path(REST_REQUEST_CONTEXT)
.queryParam("search_str", searchAddress)
.request(MediaType.APPLICATION_JSON)
.get(ResponseObject.class);
...它失败并显示“从输入流中读取实体时出错”。这是我当前的ObjectMapper设置:
defaultObjectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true)
.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true)
.configure(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS, true)
.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
.configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true)
.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)
我的ResponseObject是一个JAXB对象:
public class ResponseObject
implements Serializable
{
private final static long serialVersionUID = 1L;
protected Boolean success;
@XmlElement(nillable = true)
protected List<Result> results;
@XmlElement(nillable = true)
protected Error error;
可以优雅地处理 “results”:null ,还是应该与服务提供商合作返回空列表?
答案 0 :(得分:0)
我认为空结果是问题我错了。 Error jaxb类型是使用以下模式类型定义的:
<xs:complexType name="Error">
<xs:sequence>
<xs:element minOccurs="0" name="code" type="xs:int" />
<xs:element minOccurs="0" name="message" nillable="true" type="xs:string" />
<xs:element minOccurs="0" name="details" nillable="true"
type="q1:ArrayOfstring" xmlns:q1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" />
</xs:sequence>
</xs:complexType>
...导致以下JAXB类型:
public class Error {
protected Integer code;
@XmlElement(nillable = true)
protected String message;
@XmlElement(nillable = true)
protected ArrayOfstring details;
但是当我将架构更改为:
<xs:complexType name="Error">
<xs:sequence>
<xs:element minOccurs="0" name="code" type="xs:int" />
<xs:element minOccurs="0" name="message" nillable="true" type="xs:string" />
<!--
<xs:element minOccurs="0" name="details" nillable="true"
type="q1:ArrayOfstring" xmlns:q1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" />
-->
<xs:element minOccurs="0" name="details" maxOccurs="unbounded" nillable="true" type="xs:string" />
</xs:sequence>
</xs:complexType>
...以下JAXB类型有效:
public class Error {
private final static long serialVersionUID = 1L;
protected Integer code;
@XmlElement(nillable = true)
protected String message;
@XmlElement(nillable = true)
protected List<String> details;