Springboot中使⽤WebService和对象XML之间的转换
Spring boot中使⽤WebService
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>f</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>2.7.18</version>
</dependency>
<dependency>
<groupId>f</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>2.7.18</version>
</dependency>
<!--使⽤XStream-->
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.10</version>
</dependency>
调⽤WebService
public static Properties setting = Config("setting.properties");//获取配置⽂件中的数据
JaxWsDynamicClientFactory dcf = wInstance();
Client client = PropValue( setting ,"setting.hisWebserviceJkkAddress"));//服务地址
HTTPConduit conduit =(Conduit();
HTTPClientPolicy policy =new HTTPClientPolicy();
policy.setConnectionTimeout(10000);
policy.setAllowChunking(false);
policy.setReceiveTimeout(10000);
conduit.setClient(policy);
QName operateQName=new PropValue( setting ,"setting.jkk_namespace_url"),PropValue( setting ,"a ns_code_jkk_query"));//命名和函数
Object[] invokeResult =new Object[0];
try{
invokeResult = client.invoke(operateQName, inXml);
}catch(Exception e){
<("调⽤健康卡平台出错{}",e.getMessage());
}
String outXml=invokeResult[0].toString();
XML转对象⼯具类
注意:
public class XsteamUtil {
public static Object toBean(Class<?> clazz, String xml){
Object xmlObject = null;
XStream xstream =new XStream();
//不使⽤默认的类加载器,需要⼿动设置类加载器
xstream.setClassLoader(ClassLoader());
//安全防护
XStream.setupDefaultSecurity(xstream);
//每转换⼀个实体需要加⼊到这个数组。
xstream.allowTypes(new Class[]{JKKResult.class, PatientOutxml.class, PatientOutXml.class, BaseInxml.class, PatrentInData.class}); xstream.processAnnotations(clazz);
xstream.autodetectAnnotations(true);
xmlObject = xstream.fromXML(xml);
return xmlObject;
}
}
对象转XML⼯具类
@Slf4j
public class XMLUtil {
/**
* 将对象直接转换成String类型的 XML输出
*
* @param obj
* @return
*/
public static String convertToXml(Object obj){
// 创建输出流
StringWriter sw =new StringWriter();
try{
// 利⽤jdk中⾃带的转换类实现
JAXBContext context = Class());
Marshaller marshaller = ateMarshaller();
// 格式化xml输出的格式
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
/
/ 将对象转换成输出流形式的xml
marshaller.marshal(obj, sw);
}catch(MarshalException e1){
<("error1:{}",e1.getMessage());
e1.printStackTrace();
}catch(JAXBException e){
<("error:{}",e.getMessage());
e.printStackTrace();
}
String();
}
调用webservice服务}
实体中所需的改变
类上的注解
@XmlAccessorType(XmlAccessType.FIELD)//将字段绑定xml
@XStreamAlias("data")//如果类名和标签名不匹配,⽤此注解进⾏映射
⽅法上的注解:
@XmlElement(name ="hosCardNo")//映射属性名和标签名
转换集合:
@XStreamImplicit(itemFieldName ="deptInfo")
private List<Departments> departments;
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论