我调用一些web服务(在Ruby中构建),得到的JSON响应是这样的。
{ "error_code": "02", "message": "Param not valid", "field_name": "title"}。
为了在Java中对该响应对象进行建模,我尝试用。
import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name = "response")public class Response { private String error_code; private String message; private String field_name; public String getError_code() { return error_code; } public void setError_code(String error_code) { this. error_code = error_code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getField_name() { return field_name; } public void setField_name(String field_name) { this.field_name = field_name; }}。
......在我的WS客户端中读取WS调用的响应,我尝试着。
Response response = responseWs.readEntity(Response.class)。
... 但我得到了以下异常:
org.jboss.resteasy.plugins.providers.jaxb.JAXBUnmarshalException: javax.xml.bind.UnmarshalException - with linked exception: [com.sun.istack.internal.SAXParseException2;columnNumber: 0 unexpected element ...。预期的元素是
这是因为我的代码试图像这样处理JSON响应对象(带有一些 "根 "元素)。
{ "response": { "error_code": "02", "message": "Param not valid", "field_name": "title" } }
有人知道我这边怎么解决这个情况吗?
谅谅
从你发布的代码片段来看
Response response = responseWs.readEntity(Response.class)。
我建议为你的实体对象使用一些其他的名字。Response
jaxrs框架本身也使用class。
我假设你使用的是 RestEasyClient
来调用这个(外部)服务来接收JSON。如果明白这个服务的响应是JSON格式的,你可以使用JSON(jackson)marshallerunmarshaller代替JAXB。假设你的classpath上已经有了 "resteasy-client "的依赖。这个依赖关系的maven形式如下。
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>3.0.19.Final</version>
</dependency>
ExternalServiceResponse
GET
您明确指定响应媒体类型的请求Response response = target.request(MediaType.APPLICATION_JSON).get();
ExternalServiceResponse result = response.readEntity(ExternalServiceResponse.class)
@XmlRootElement
在您的DTO上做注解public class ExternalServiceResponse implements Serializeable {
private String error_code;
private String message;
private String field_name;
public String getError_code() {
return error_code;
}
public void setError_code(String error_code) {
this.error_code = error_code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getField_name() {
return field_name;
}
public void setField_name(String field_name) {
this.field_name = field_name;
}
}
在配置JAXB的地方(属性文件或配置方法),你应该设置为 jaxbUnmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false)
对我来说,这个片段解决了这个问题。
String responseAsString = responseWs.readEntity(String.class);
ObjectMapper mapper = new ObjectMapper();
JsonNode pathNode = mapper.readTree(responseAsString);
Response response = mapper.convertValue(pathNode, Response.class);