[英]How to map soap response object containing JAXBElement to another POJO?
我创建了一个 jax-ws 客户端并拨打了肥皂电话。 它工作得很好,但是当我从soap调用收到的响应作为json对象返回时我遇到了问题。
这就是我调用 SOAP 服务并获得响应的方式:
@Override
public GetUserResponse getUser(Integer userId) {
ObjectFactory objectFactory = new ObjectFactory();
GetUserRequest getUserRequest = objectFactory.createGetUserRequest();
getUserRequest.setUserId(userId);
GetUserResponse response = getClient().getUser(getUserRequest);
return response;
}
问题是, GetUserResponse
是使用wsimport
生成的,当我将此响应作为 JSON 对象返回时,它有很多不必要的字段。 这是它的外观:
{
"user":{
"name":"{http://www.myservicedomain.com/service}User",
"declaredType":"com.example.demo.User",
"scope":"com.example.demo.GetUserResponse",
"value":{
"userId":{
"name":"{http://www.myservicedomain.com/service}UserId",
"declaredType":"java.lang.Integer",
"scope":"com.example.demo.User",
"value":88938134,
"nil":false,
"globalScope":false,
"typeSubstituted":false
},
"name":{
"name":"{http://www.myservicedomain.com/service}Name",
"declaredType":"java.lang.String",
"scope":"com.example.demo.User",
"value":"",
"nil":false,
"globalScope":false,
"typeSubstituted":false
},
"active":{
"name":"{http://www.myservicedomain.com/service}Active",
"declaredType":"java.lang.Boolean",
"scope":"com.example.demo.User",
"value":true,
"nil":false,
"globalScope":false,
"typeSubstituted":false
},
"postalCode":{
"name":"{http://www.myservicedomain.com/service}PostalCode",
"declaredType":"java.lang.String",
"scope":"com.example.demo.Address",
"value":null,
"nil":true,
"globalScope":false,
"typeSubstituted":false
}
}
}
}
但我只想返回字段的值,如下所示:
{
"user":{
"userId": 88938134,
"name": "My name",
"active": true,
"postalCode": null
}
}
我可以像这样手动挖掘响应并提取值,但这需要大量代码并且可能不是一个好习惯。
GetUserResponse response = getClient().getUser(getUserRequest);
User user = response.getUser().getValue();
JAXBElement<String> name = user.getName();
String nameValue = name.getValue();
//etc..
有没有办法做到这一点?
谢谢你。
我在这里找到了解决方案。 原因是,WSDL 声明这些字段既是可选的又是可空的。 这就是为什么我在生成的类中有 JAXBElement 的原因。 我使用带有wsimport
命令的绑定文件并重新生成了类。
绑定文件:
<jaxb:bindings version="2.1"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<jaxb:globalBindings generateElementProperty="false"/>
</jaxb:bindings>
和命令:
wsimport -keep <WSDL_location> -b binding.xml
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.