JAXB實現XML和java對象互轉以及soapXml和對象互轉需要注意的地方

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點

感謝偶然間看到這個 帖子 和這個 博客
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章