javascript
Spring OXM-XStream使用别名
- 導(dǎo)讀
- 別名配置的三種情況
- 官方Demo
- 問題
- Model
- A Simple Test
- Class aliasing
- Field aliasing
- Implicit Collections
- Attribute aliasing
- Package aliasing
- 示例源碼
導(dǎo)讀
在Spring OXM-XStream快速入門 的案例中,我們看到生成的xml報文如下:
<com.xgj.oxm.xstream.quickDemo.domain.User><id>1</id><userName>Artisan</userName><password>artisan</password><credits>1000</credits><lastVisit>2017-12-05 07:30:46.772 UTC</lastVisit><logs><com.xgj.oxm.xstream.quickDemo.domain.LoginLog><loginLogId>99</loginLogId><userId>1</userId><ip>127.0.0.1</ip><loginDate>2017-12-05 07:30:46.772 UTC</loginDate></com.xgj.oxm.xstream.quickDemo.domain.LoginLog></logs> </com.xgj.oxm.xstream.quickDemo.domain.User>在默認情況下,Java對象到XML的映射是Java對象屬性名對應(yīng)XML的元素名,Java類的全名對應(yīng)XML根元素的名字。
事實上,在實際應(yīng)用中,如果XML和Java類都已經(jīng)存在相應(yīng)的名稱,那么在進行轉(zhuǎn)換時,需要設(shè)置別名進行映射。
別名配置的三種情況
類別名: 使用alias(String name,Class type)
類成員別名:使用aliasField(String alias, Class definedIn, String fieldName)
類成員作為xml屬性別名:使用aliasAttribute(Class definedIn, String attributeName, String alias)方法。 并且需要通過 useAttributeFor(Class definedIn, String fieldName) 應(yīng)用到某個類上。
從上面的實例中我們看到XML元素結(jié)構(gòu)不是很友好,接下來我們通過XStream提供的別名機制來修飾生成的XML元素的結(jié)構(gòu)。
package com.xgj.oxm.xstream.quickDemo.aliasDemo;import java.text.ParseException; import java.util.Date;import com.thoughtworks.xstream.XStream; import com.xgj.oxm.xstream.quickDemo.domain.LoginLog; import com.xgj.oxm.xstream.quickDemo.domain.User;public class XStreamAliasDemo {private static XStream xstream;static {// 創(chuàng)建一個Xstream實例,使用默認的XPP解析器xstream = new XStream();// (1)設(shè)置類別名,修改默認的全限定名的名稱xstream.alias("user", User.class);xstream.alias("loginLog", LoginLog.class);// (2)設(shè)置類成員別名 <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>標(biāo)記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));System.out.println("objectToXml successfully");}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-05 13:39:32.698 UTC</lastVisit><loginLog id="1"><loginLogId>99</loginLogId><ip>127.0.0.1</ip><loginDate>2017-12-05 13:39:32.698 UTC</loginDate></loginLog><loginLog id="2"><loginLogId>22</loginLogId><ip>192.168.1.1</ip><loginDate>2017-12-05 13:39:32.698 UTC</loginDate></loginLog> </user>說明:
在(1)處,通過XStream的alias方法來設(shè)置類別名。
在(2)處,通過XStream的aliasField方法將User類的id屬性設(shè)置為userId
在(3)處,通過XStream的aliasAttribute和useAttributeFor方法將LoginLog類的userId屬性設(shè)置為id,并設(shè)置為LoginLog元素的屬性。 默認為LoginLog元素的子元素。
在(4)處,通過XStream的addImplicitCollection方法刪除集合節(jié)點logs,即忽略XML中的<logs></logs>標(biāo)記。
官方Demo
問題
假設(shè)我們有如下的XML,我們?nèi)绾问褂肵Stream去讀寫呢?
<blog author="Guilherme Silveira"><entry><title>first</title><description>My first blog entry.</description></entry><entry><title>tutorial</title><description>Today we have developed a nice alias tutorial. Tell your friends! NOW!</description></entry> </blog>結(jié)合XStream中的方法,我們來分析一下
blog 節(jié)點有個 author 屬性 ,可以使用aliasAttribute 和 useAttributeFor方法應(yīng)用到Blog類上,也可以使用XStream的轉(zhuǎn)換器,這里我們使用轉(zhuǎn)換器的方式。 因為要使用轉(zhuǎn)換器,所以需要一個Author類以及對應(yīng)的一個name屬性用于存儲name的值
子節(jié)點是多個entry,可以使用List來存儲
entry節(jié)點有title 和 description 屬性 ,所以需要一個Entry類以及2個屬性
Model
接下來我們來看下我們創(chuàng)建的幾個model類
package com.xgj.oxm.xstream.quickDemo.aliasDemo.officeDemo;import java.util.ArrayList; import java.util.List;public class Blog {// Authorprivate Author writer;// Entry集合private List<Entry> entries = new ArrayList<Entry>();/*** * * @Title:Blog* * @Description:構(gòu)造函數(shù)* * @param writer*/public Blog(Author writer) {this.writer = writer;}/*** * * @Title: add* * @Description: 添加Entry* * @param entry* * @return: void*/public void add(Entry entry) {entries.add(entry);}/*** * * @Title: getContent* * @Description: 獲取Entry List集合* * @return* * @return: List<Entry>*/public List<Entry> getContent() {return entries;} } package com.xgj.oxm.xstream.quickDemo.aliasDemo.officeDemo;public class Author {private String name;public Author(String name) {this.name = name;}public String getName() {return name;} } package com.xgj.oxm.xstream.quickDemo.aliasDemo.officeDemo;public class Entry {private String title, description;public Entry(String title, String description) {this.title = title;this.description = description;} }我們沒有創(chuàng)建set/get方法,可根據(jù)需要創(chuàng)建。
A Simple Test
接下來,我們來測試一下
public static void main(String[] args) {Blog teamBlog = new Blog(new Author("Guilherme Silveira"));teamBlog.add(new Entry("first","My first blog entry."));teamBlog.add(new Entry("tutorial","Today we have developed a nice alias tutorial. Tell your friends! NOW!"));XStream xstream = new XStream();System.out.println(xstream.toXML(teamBlog));}輸出如下
<com.xgj.oxm.xstream.quickDemo.aliasDemo.officeDemo.Blog><writer><name>Guilherme Silveira</name></writer><entries><com.xgj.oxm.xstream.quickDemo.aliasDemo.officeDemo.Entry><title>first</title><description>My first blog entry.</description></com.xgj.oxm.xstream.quickDemo.aliasDemo.officeDemo.Entry><com.xgj.oxm.xstream.quickDemo.aliasDemo.officeDemo.Entry><title>tutorial</title><description>Today we have developed a nice alias tutorial. Tell your friends! NOW!</description></com.xgj.oxm.xstream.quickDemo.aliasDemo.officeDemo.Entry></entries> </com.xgj.oxm.xstream.quickDemo.aliasDemo.officeDemo.Blog>Class aliasing
我們需要把com.xgj.oxm.xstream.quickDemo.aliasDemo.officeDemo.Blog 和 com.xgj.oxm.xstream.quickDemo.aliasDemo.officeDemo.Entry 轉(zhuǎn)換成 blog 和 entry.
通過
xstream.alias("blog", Blog.class);xstream.alias("entry", Entry.class); Blog teamBlog = new Blog(new Author("Guilherme Silveira"));teamBlog.add(new Entry("first", "My first blog entry."));teamBlog.add(new Entry("tutorial","Today we have developed a nice alias tutorial. Tell your friends! NOW!"));XStream xstream = new XStream();// alias Classxstream.alias("blog", Blog.class);xstream.alias("entry", Entry.class);System.out.println(xstream.toXML(teamBlog));輸出結(jié)果如下
<blog><writer><name>Guilherme Silveira</name></writer><entries><entry><title>first</title><description>My first blog entry.</description></entry><entry><title>tutorial</title><description>Today we have developed a nice alias tutorial. Tell your friends! NOW!</description></entry></entries> </blog>Field aliasing
下面把wirter轉(zhuǎn)換為 author .通過
xstream.aliasField("author", Blog.class, "writer");輸出如下
<blog><author><name>Guilherme Silveira</name></author><entries><entry><title>first</title><description>My first blog entry.</description></entry><entry><title>tutorial</title><description>Today we have developed a nice alias tutorial. Tell your friends! NOW!</description></entry></entries> </blog>Implicit Collections
去掉entries節(jié)點,通過
xstream.addImplicitCollection(Blog.class, "entries");輸出如下
<blog><author><name>Guilherme Silveira</name></author><entry><title>first</title><description>My first blog entry.</description></entry><entry><title>tutorial</title><description>Today we have developed a nice alias tutorial. Tell your friends! NOW!</description></entry> </blog>Attribute aliasing
下一步是將writer成員變量轉(zhuǎn)換為xml的屬性 , 為了做到這一點,我們需要告訴XStream將Blog#writer字段同義為author
問題 : how does XStream converts an Author in a String so it can be written as a XML tag attribute?
Attributes cannot be written for types that are handled by Converter implementations, we have to use a SingleValueConverter and implement our own converter for the Author:
package com.xgj.oxm.xstream.quickDemo.aliasDemo.officeDemo;import com.thoughtworks.xstream.converters.SingleValueConverter;public class AuthorConverter implements SingleValueConverter {/*** tells XStream which types it can deal with*/public boolean canConvert(Class type) {return type.equals(Author.class);}/*** extract a String from an Author*/public String toString(Object obj) {return ((Author) obj).getName();}/*** takes a String and returns an Author*/public Object fromString(String name) {return new Author(name);} }然后注冊轉(zhuǎn)換器
xstream.useAttributeFor(Blog.class, "writer"); xstream.registerConverter(new AuthorConverter());完整的代碼如下
package com.xgj.oxm.xstream.quickDemo.aliasDemo.officeDemo;import com.thoughtworks.xstream.XStream;public class AliasTest {public static void main(String[] args) {Blog teamBlog = new Blog(new Author("Guilherme Silveira"));teamBlog.add(new Entry("first", "My first blog entry."));teamBlog.add(new Entry("tutorial","Today we have developed a nice alias tutorial. Tell your friends! NOW!"));XStream xstream = new XStream();xstream.alias("blog", Blog.class);xstream.alias("entry", Entry.class);xstream.aliasField("author", Blog.class, "writer");xstream.addImplicitCollection(Blog.class, "entries");xstream.useAttributeFor(Blog.class, "writer");xstream.registerConverter(new AuthorConverter());System.out.println(xstream.toXML(teamBlog));} }輸出
<blog author="Guilherme Silveira"><entry><title>first</title><description>My first blog entry.</description></entry><entry><title>tutorial</title><description>Today we have developed a nice alias tutorial. Tell your friends! NOW!</description></entry> </blog>Package aliasing
xstream.aliasPackage("my.company", "org.thoughtworks");比如
package com.xgj.oxm.xstream.quickDemo.aliasDemo.officeDemo;import com.thoughtworks.xstream.XStream;public class AliasPackage {public static void main(String[] args) {Blog teamBlog = new Blog(new Author("Guilherme Silveira"));teamBlog.add(new Entry("first", "My first blog entry."));teamBlog.add(new Entry("tutorial","Today we have developed a nice alias tutorial. Tell your friends! NOW!"));XStream xstream = new XStream();xstream.aliasPackage( "com.artisan","com.xgj.oxm.xstream.quickDemo.aliasDemo.officeDemo");System.out.println(xstream.toXML(teamBlog));}}輸出
<com.artisan.Blog><writer><name>Guilherme Silveira</name></writer><entries><com.artisan.Entry><title>first</title><description>My first blog entry.</description></com.artisan.Entry><com.artisan.Entry><title>tutorial</title><description>Today we have developed a nice alias tutorial. Tell your friends! NOW!</description></com.artisan.Entry></entries> </com.artisan.Blog>示例源碼
代碼已托管到Github—> https://github.com/yangshangwei/SpringMaster
總結(jié)
以上是生活随笔為你收集整理的Spring OXM-XStream使用别名的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring OXM-XStream快速
- 下一篇: Spring OXM-XStream转换