javascript
Spring OXM-XStream转换器
- 概述
- 示例
- 示例源碼
概述
我們在開發(fā)的過程中,有的時候需要轉(zhuǎn)換一些自定義類型,此時默認的映射方式可能無法滿足需要。
XStream為我們提供了豐富的擴展,用戶可以實現(xiàn)自己的轉(zhuǎn)換器,然后調(diào)用registerConverter方法注冊自定義的轉(zhuǎn)換器。
實現(xiàn)自定義的轉(zhuǎn)換器很簡單,只需要實現(xiàn)XStream提供的Converter接口并實現(xiàn)其方法即可。
示例
我們在上個案例中的代碼
package com.xgj.oxm.xstream.quickDemo.convert;import java.text.ParseException; import java.util.Date; import java.util.Locale;import com.thoughtworks.xstream.XStream; import com.xgj.oxm.xstream.quickDemo.domain.LoginLog; import com.xgj.oxm.xstream.quickDemo.domain.User;public class XStreamConverterDemo {private static XStream xstream;static {// 創(chuàng)建一個Xstream實例,使用默認的XPP解析器xstream = new XStream();// (1)設置類別名,修改默認的全限定名的名稱xstream.alias("user", User.class);xstream.alias("loginLog", LoginLog.class);// (2)設置類成員別名 <id>1</id> 改為<userId>1</userId>xstream.aliasField("userId", User.class, "id");// (3)把LoginLog的userId屬性視為xml屬性,默認為xml的元素xstream.aliasAttribute(LoginLog.class, "userId", "id");xstream.useAttributeFor(LoginLog.class, "userId");// (4)去掉集合類型生成XML的父節(jié)點,即忽略xml中的<logs></logs>標記xstream.addImplicitCollection(User.class, "logs");}/*** * * @Title: getUser* * @Description: 初始化轉(zhuǎn)換對象* * @return* * @return: User* @throws ParseException*/public static User getUser() throws ParseException {LoginLog log = new LoginLog();log.setIp("127.0.0.1");log.setLoginLogId(99);log.setUserId(1);log.setLoginDate(new Date());LoginLog log2 = new LoginLog();log2.setIp("192.168.1.1");log2.setLoginLogId(22);log2.setUserId(2);log2.setLoginDate(new Date());User user = new User();user.setId(1);user.setUserName("Artisan");user.setPassword("artisan");user.setCredits(1000);user.setLastVisit(new Date());user.addLoginLog(log);user.addLoginLog(log2);return user;}/*** * * @Title: objectToXml* * @Description: Java對象轉(zhuǎn)換成XML* * @throws Exception* * @return: void*/public static void objectToXml() throws Exception {// 獲取轉(zhuǎn)換的User對象實例User user = getUser();// 輸出內(nèi)容到控制臺,查看一下System.out.println(xstream.toXML(user));}public static void main(String[] args) throws Exception {objectToXml();} }輸出如下
<user><userId>1</userId><userName>Artisan</userName><password>artisan</password><credits>1000</credits><lastVisit>2017-12-06 12:32:06.504 UTC</lastVisit><loginLog id="1"><loginLogId>99</loginLogId><ip>127.0.0.1</ip><loginDate>2017-12-06 12:32:06.504 UTC</loginDate></loginLog><loginLog id="2"><loginLogId>22</loginLogId><ip>192.168.1.1</ip><loginDate>2017-12-06 12:32:06.504 UTC</loginDate></loginLog> </user>可以看到時間格式如下:
2017-12-06 12:32:06.504 UTCUTC與格林尼治平均時(GMT, Greenwich Mean Time)一樣,都與英國倫敦的本地時相同,UTC + 時區(qū)差=本地時間
如果我們希望顯示北京時間呢?
就需要用到轉(zhuǎn)換器了
package com.xgj.oxm.xstream.quickDemo.convert;import java.text.SimpleDateFormat; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale;import com.thoughtworks.xstream.converters.ConversionException; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter;public class DateConverter implements Converter {private Locale locale;public DateConverter(Locale locale) {super();this.locale = locale;}/*** 重寫該方法,判斷需要轉(zhuǎn)換的類型*/@Overridepublic boolean canConvert(Class type) {return Date.class.isAssignableFrom(type);}/*** 重寫該方法,編寫Java 到 XML 的轉(zhuǎn)換邏輯*/@Overridepublic void marshal(Object source, HierarchicalStreamWriter writer,MarshallingContext context) {// DateFormat format = DateFormat.getDateInstance(DateFormat.DATE_FIELD,// this.locale);SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", this.locale);writer.setValue(format.format(source));}/*** 重寫該方法,編寫XML 到 Java 的轉(zhuǎn)換邏輯*/@Overridepublic Object unmarshal(HierarchicalStreamReader reader,UnmarshallingContext context) {GregorianCalendar calendar = new GregorianCalendar();// DateFormat format = DateFormat.getDateInstance(DateFormat.DATE_FIELD,// this.locale);SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",this.locale);try {calendar.setTime(format.parse(reader.getValue()));} catch (Exception e) {throw new ConversionException(e.getMessage(), e);}return calendar.getGregorianChange();}}解析
通過 canConvert 方法來判斷轉(zhuǎn)換邏輯
通過marshal方法,完成對象編組(對象轉(zhuǎn)XML)操作的處理邏輯
通過unmarshal方法,完成對象f反編組(XML轉(zhuǎn)對象)操作的處理邏輯
最后調(diào)用registerConverter方法注冊自定義的轉(zhuǎn)換器
修改生成xml的代碼注冊轉(zhuǎn)換器,完整代碼如下
package com.xgj.oxm.xstream.quickDemo.convert;import java.text.ParseException; import java.util.Date; import java.util.Locale;import com.thoughtworks.xstream.XStream; import com.xgj.oxm.xstream.quickDemo.domain.LoginLog; import com.xgj.oxm.xstream.quickDemo.domain.User;public class XStreamConverterDemo {private static XStream xstream;static {// 創(chuàng)建一個Xstream實例,使用默認的XPP解析器xstream = new XStream();// (1)設置類別名,修改默認的全限定名的名稱xstream.alias("user", User.class);xstream.alias("loginLog", LoginLog.class);// (2)設置類成員別名 <id>1</id> 改為<userId>1</userId>xstream.aliasField("userId", User.class, "id");// (3)把LoginLog的userId屬性視為xml屬性,默認為xml的元素xstream.aliasAttribute(LoginLog.class, "userId", "id");xstream.useAttributeFor(LoginLog.class, "userId");// (4)去掉集合類型生成XML的父節(jié)點,即忽略xml中的<logs></logs>標記xstream.addImplicitCollection(User.class, "logs");// 注冊轉(zhuǎn)換器xstream.registerConverter(new DateConverter(Locale.CHINESE));}/*** * * @Title: getUser* * @Description: 初始化轉(zhuǎn)換對象* * @return* * @return: User* @throws ParseException*/public static User getUser() throws ParseException {LoginLog log = new LoginLog();log.setIp("127.0.0.1");log.setLoginLogId(99);log.setUserId(1);log.setLoginDate(new Date());LoginLog log2 = new LoginLog();log2.setIp("192.168.1.1");log2.setLoginLogId(22);log2.setUserId(2);log2.setLoginDate(new Date());User user = new User();user.setId(1);user.setUserName("Artisan");user.setPassword("artisan");user.setCredits(1000);user.setLastVisit(new Date());user.addLoginLog(log);user.addLoginLog(log2);return user;}/*** * * @Title: objectToXml* * @Description: Java對象轉(zhuǎn)換成XML* * @throws Exception* * @return: void*/public static void objectToXml() throws Exception {// 獲取轉(zhuǎn)換的User對象實例User user = getUser();// 輸出內(nèi)容到控制臺,查看一下System.out.println(xstream.toXML(user));}public static void main(String[] args) throws Exception {objectToXml();} }輸出
<user><userId>1</userId><userName>Artisan</userName><password>artisan</password><credits>1000</credits><lastVisit>2017-12-06 20:34:42</lastVisit><loginLog id="1"><loginLogId>99</loginLogId><ip>127.0.0.1</ip><loginDate>2017-12-06 20:34:42</loginDate></loginLog><loginLog id="2"><loginLogId>22</loginLogId><ip>192.168.1.1</ip><loginDate>2017-12-06 20:34:42</loginDate></loginLog> </user>可以看到時間已經(jīng)是 2017-12-06 20:34:42 北京時間了。 轉(zhuǎn)換器起作用了。
示例源碼
代碼已托管到Github—> https://github.com/yangshangwei/SpringMaster
總結(jié)
以上是生活随笔為你收集整理的Spring OXM-XStream转换器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring OXM-XStream使用
- 下一篇: Spring OXM-XStream注解