JAXB實現XML和java物件互轉以及soapXml和物件互轉需要注意的地方
阿新 • • 發佈:2019-01-09
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; } }
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 、time @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點
感謝偶然間看到這個
帖子
和這個
部落格