public class JaxbXmlUtil {
private static final String DEFAULT_ENCODING = "UTF-8";
/**
* pojo转换成xml 默认编码UTF-8
*/
public static String convertBeanToXml(Object obj) throws Exception {
return convertBeanToXml(obj, DEFAULT_ENCODING);
}
/**
* pojo转换成xml
*/
public static String convertBeanToXml(Object obj, String encoding) throws Exception {
String result;
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
// 生成报文的格式化
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
StringWriter writer = new StringWriter();
marshaller.marshal(obj, writer);
result = writer.toString();
return result;
}
/**
* xml转换成pojo
*/
@SuppressWarnings("unchecked")
public static <T> T convertXmlToJavaBean(String xml, Class<T> t) throws Exception {
T obj;
JAXBContext context = JAXBContext.newInstance(t);
Unmarshaller unmarshaller = context.createUnmarshaller();
obj = (T) unmarshaller.unmarshal(new StringReader(xml));
return obj;
}
}
public class TestJaxbClass {
/**
* 调用示例
*/
public static void main(String[] args) {
String respXml = "xml报文";
// 将返回报文转成对象 (ResponseDTO 修改成你需要的对象)
ResponseDTO respDTO = JaxbXmlUtil.convertXmlToJavaBean(respXml, ResponseDTO.class);
}
}
jaxb:xml和pojo相互转换,上面这种工具类就不说了,看代码就行 这次主要是soapXML请求webservice接口,返回报文再进行解析。
本来使用的wsdl直接生成客户端代码,但由于种种原因最后选择了org.apache.commons.httpclient 调用webservice的接口
就想仿照生成的客户端代码自己写下转换
这里主要说一下使用时需要注意的地方(这次遇到的两个坑) pojo---》soapXML:
1: 需要用到xml格式的时间时注意中间有个T 如:<trxDate>2017-11-05T02:57:56</trxDate> 转换的时候注意下边的name
值为dateTime ,切不可写成date
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar trxDate;
2: 生成的soap XML报文如果有多个xmlns:的情况,请检查pojo里面字段或引入对象的namespace
3: 如果有别名需要,请注意 @XmlElement 的name自定义
soapXML---》:pojo
1:javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"xxx")
这种错误就是xml转对象的时候不识别造成的,需要在对应的对象或字段上加上别名namespace
(就是你报错信息中的uri)即可。 这个错误花了一天多才理清,嗯现在是凌晨3点
感谢偶然间看到这个 帖子 和这个 博客