将xmlbean结构的javabean转stringg转换成xmlbean对象有几种实现方式

当前访客身份:游客 [
:引用来自“shihaitao2004”的评论DocumentVo 能支...
:DocumentVo 能支持数组属性吗?
:引用来自“果然没注册”的评论你好,最近公司项目...
:引用来自“steel”的评论测试了下,原先html的中...
:测试了下,原先html的中文是乱码,填充的数据内容...
:大爷的!转载请写明出处!
:引用来自“果然没注册”的评论你好,最近公司项目...
:引用来自“果然没注册”的评论你好,最近公司项目...
:配置有效,感谢!
:引用来自“果然没注册”的评论你好,最近公司项目...
今日访问:1
昨日访问:11
本周访问:1
本月访问:78
所有访问:13397
XML与对象之间转换
发表于2年前( 18:54)&&
阅读(2814)&|&评论()
0人收藏此文章,
xml与对象javabean之间转换,对象生成soap报文xml,soap报文xml转换为对象
使用jaxb 实现对象与xml之间的转换,并且是 soap报文与对象转换
1.测试用例
public class TestJaxb {
public void testToObject(){
JaxbBinder jaxbBinder = new JaxbBinder(SoapEnvelope.class);
URL url = this.getClass().getClassLoader().getResource("receB2COrderResponse.xml");
String xml =
xml = FileUtils.readFileToString(new File(url.getPath())) ;
} catch (IOException e) {
e.printStackTrace();
//To change body of catch statement use File | Settings | File Templates.
SoapEnvelope envelope =jaxbBinder.fromXml(xml);
Assert.notNull(envelope,"envelope数据为空");
Assert.notNull(envelope.getBody(),"body数据为空");
Assert.notNull(envelope.getBody().getReceB2COrderResponseList(),"body.list数据为空");
Assert.notNull(envelope.getBody().getReceB2COrderResponseList().get(0),"body.list[0]数据为空");
Assert.notNull(envelope.getBody().getReceB2COrderResponseList().get(0).getOrderNo(),"body.list[0]数据为空");
System.out.println("getOrderNo="+envelope.getBody().getReceB2COrderResponseList().get(0).getOrderNo());
System.out.println("\ndata="+ (envelope).toString());
public void testToXml(){
ReceB2COrderRequest re = new ReceB2COrderRequest();
re.setBuyerContact("test");
re.setBuyerId("asdfsadfasdf");
re.setBuyerName("aaaaaaaaaaa");
SoapBody body = new SoapBody();
body.setReceB2COrderRequestList(Arrays.asList(re));
SoapEnvelope envelope = new SoapEnvelope(null,body);
JaxbBinder jaxbBinder = new JaxbBinder(SoapEnvelope.class);
String xml =jaxbBinder.toXml(envelope,"utf-8");
System.out.println("\nxml="+ xml);
} 2.转换工具
import javax.xml.bind.*;
import javax.xml.namespace.QN
import java.io.F
import java.io.InputS
import java.io.StringR
import java.io.StringW
import java.util.C
* 使用Jaxb2.0实现XML&-&Java Object的Binder.
* 特别支持Root对象是List的情形.
public class JaxbBinder {
//多线程安全的Context.
private JAXBContext jaxbC
* @param types 所有需要序列化的Root对象的类型.
public JaxbBinder(Class&?&... types) {
jaxbContext = JAXBContext.newInstance(types);
} catch (JAXBException e) {
throw new RuntimeException(e);
* Java Object-&Xml.
public String toXml(Object root, String encoding) {
StringWriter writer = new StringWriter();
createMarshaller(encoding).marshal(root, writer);
return writer.toString();
} catch (JAXBException e) {
throw new RuntimeException(e);
* Java Object-&Xml, 特别支持对Root Element是Collection的情形.
@SuppressWarnings("unchecked")
public String toXml(Collection root, String rootName, String encoding) {
CollectionWrapper wrapper = new CollectionWrapper();
wrapper.collection =
JAXBElement&CollectionWrapper& wrapperElement = new JAXBElement&CollectionWrapper&(new QName(rootName),
CollectionWrapper.class, wrapper);
StringWriter writer = new StringWriter();
createMarshaller(encoding).marshal(wrapperElement, writer);
return writer.toString();
} catch (JAXBException e) {
throw new RuntimeException(e);
* Xml-&Java Object.
@SuppressWarnings("unchecked")
public &T& T fromXml(String xml) {
StringReader reader = new StringReader(xml);
return (T) createUnmarshaller().unmarshal(reader);
} catch (JAXBException e) {
throw new RuntimeException(e);
* 创建Marshaller, 设定encoding(可为Null).
public Marshaller createMarshaller(String encoding) {
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
if (StringUtils.isNotBlank(encoding)) {
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
} catch (JAXBException e) {
throw new RuntimeException(e);
* 创建UnMarshaller.
public Unmarshaller createUnmarshaller() {
return jaxbContext.createUnmarshaller();
} catch (JAXBException e) {
throw new RuntimeException(e);
* 封装Root Element 是 Collection的情况.
public static class CollectionWrapper {
@SuppressWarnings("unchecked")
@XmlAnyElement
protected C
@SuppressWarnings("unchecked")
public &T& T fromXML(String fileName) {
return (T)fromXML(new File(fileName));
@SuppressWarnings("unchecked")
public &T& T fromXML(File file) {
Unmarshaller unmarshaller = createUnmarshaller();
return (T) unmarshaller.unmarshal(file);
} catch (JAXBException e) {
throw new RuntimeException(e);
@SuppressWarnings("unchecked")
public &T& T fromXML(InputStream stream) {
Unmarshaller unmarshaller = createUnmarshaller();
return (T) unmarshaller.unmarshal(stream);
} catch (JAXBException e) {
throw new RuntimeException(e);
3.XML报文实例(receB2COrderResponse.xml)
&soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"&
&soap:Body&
&&& &ns1:receiveB2COrderResponse xmlns:ns1="/mas/api/receive/"&
&&&&&&& &return&
&&&&&&&&&&& &customerName&爱奇艺&/customerName&
&&&&&&&&&&& &customerNo&332396&/customerNo&
&&&&&&&&&&& &orderAmount&30.00&/orderAmount&
&&&&&&&&&&& &orderNo&1210442&/orderNo&
&&&&&&&&&&& &orderType&OT001&/orderType&
&&&&&&&&&&& &returnInfo/&
&&&&&&&&&&& &sessionId&d40-42dc-afec-980cbf0122a4&/sessionId&
&&&&&&&&&&& &signature/&
&&&&&&&&&&& &tokenId&4A8A8F14C3BEDAAFD91E5B2982EAB21DDE8C557FC5A52B887E8CBF9AE3B19&/tokenId&
&&&&&&&&&&& &transNo&C&/transNo&
&&&&&&&&&&& &transStatus&00&/transStatus&
&&&&&&&&&&& &transTime&18&/transTime&
&&&&&&& &/return&
&&& &/ns1:receiveB2COrderResponse&
&/soap:Body&
&/soap:Envelope& 4.testToXml()输出的报文内容:
&?xml version="1.0" encoding="UTF-8"?&
&soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:rec="/mas/api/receive/"&
&soapenv:Header&
&/soapenv:Header&
&soapenv:Body&
&rec:receiveB2COrder&
&buyerContact&&/buyerContact&
&buyerId&&/buyerId&
&buyerIp&&/buyerIp&
&buyerName&&/buyerName&
&cardPayInfo&&/cardPayInfo&
&cardValue&&/cardValue&
&currency&CNY&/currency&
&depositId&&/depositId&
&depositIdType&&/depositIdType&
&expireTime&&/expireTime&
&instCode&&/instCode&
&language&zh-CN&/language&
&notifyUrl&sntCode=sdocard&/notifyUrl&
&orderAmount&1.00&/orderAmount&
&orderNo&4151822&/orderNo&
&orderTime&41&/orderTime&
&pageUrl&fdction?paymentCode=sdocard&/pageUrl&
&payChannel&&/payChannel&
&payType&&/payType&
&payeeId&&/payeeId&
&payerAuthTicket&&/payerAuthTicket&
&payerId&&/payerId&
&payerMobileNo&&/payerMobileNo&
&productDesc&&/productDesc&
&productId&&/productId&
&productName&&/productName&
&productNum&&/productNum&
&productUrl&&/productUrl&
&sellerId&&/sellerId&
&terminalType&&/terminalType&
&unitPrice&&/unitPrice&
&/rec:receiveB2COrder&
&/soapenv:Body&
&/soapenv:Envelope&
5.java的对象(省略了getter/setter)
&&&&@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Envelope", namespace = NAMESPACE_OF_ENVELOPE)
public class SoapEnvelope {
&&&&&&&&&&& /**
&&&& * soap 中 envelope namespace
&&& &&&&public static final String NAMESPACE_OF_ENVELOPE = "http://schemas.xmlsoap.org/soap/envelope/";
&&&& * soap 中 receiveB2COrderResponse namespace
&&& &&&&public static final String NAMESPACE_OF_RECEIVEB2CORDER = "/mas/api/receive/";
&&&&&&& @XmlElement(name = "Header", namespace = NAMESPACE_OF_ENVELOPE)
private SoapH
@XmlElement(name = "Body", namespace = NAMESPACE_OF_ENVELOPE )
private SoapB
@XmlAccessorType(XmlAccessType.FIELD)
public class SoapBody {
&&&&&&& &&& /**
&&&& * soap 中 envelope namespace
&&& &&&&public static final String NAMESPACE_OF_ENVELOPE = "http://schemas.xmlsoap.org/soap/envelope/";
&&&& * soap 中 receiveB2COrderResponse namespace
&&& &&&&public static final String NAMESPACE_OF_RECEIVEB2CORDER = "/mas/api/receive/";
&&&&&&&&@XmlElement(name = "Fault", namespace = NAMESPACE_OF_ENVELOPE)
@XmlElementWrapper(name = "receiveB2COrder", namespace = NAMESPACE_OF_RECEIVEB2CORDER)
@XmlElement(name = "arg0")
private List&ReceB2COrderRequest& receB2COrderRequestL
@XmlElementWrapper(name = "receiveB2COrderResponse", namespace = NAMESPACE_OF_RECEIVEB2CORDER)
@XmlElement(name = "return")
private List&ReceB2COrderResponse& receB2COrderResponseL
@XmlAccessorType(XmlAccessType.FIELD)
public class ReceB2COrderRequest {
private String orderNo;
private String orderA
private String orderT
private String expireT
private String payT
private String payC
private String instC
private String cardV
private String pageU
private String notifyU
@XmlAccessorType(XmlAccessType.FIELD)
public class ReceB2COrderResponse{
private String orderNo;
private String transNo;
private String customerN
private String customerNo;
private String customerLogoU
private String orderT
private String orderA
private String transS
private String transT
private String tokenId;
private String sessionId;
&&& @XmlAccessorType(XmlAccessType.FIELD)
&&& public static class SoapHeader {
更多开发者职位上
1)">1)">1" ng-class="{current:{{currentPage==page}}}" ng-repeat="page in pages"><li class='page' ng-if="(endIndex<li class='page next' ng-if="(currentPage
相关文章阅读XMLBean使用总结_百度文库
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
XMLBean使用总结
上传于||暂无简介
阅读已结束,如果下载本文需要使用2下载券
想免费下载本文?
下载文档到电脑,查找使用更方便
还剩9页未读,继续阅读
你可能喜欢二次元同好交流新大陆
扫码下载App
汇聚2000万达人的兴趣社区下载即送20张免费照片冲印
扫码下载App
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!&&|&&
LOFTER精选
网易考拉推荐
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
import java.beans.IntrospectionE
import java.io.IOE
import java.io.StringR
import java.io.StringW
import mons.betwixt.io.BeanR
import mons.betwixt.io.BeanW
import org.xml.sax.SAXE
import com.pobasoft.ws.Bean.SelectUserIDListB
public class XMLAndBeanUtil {
&&&&&&&& /**
&&&&&&&& * 将xml字符串转化为对象
&&&&&&&& *
&&&&&&&& * @param xmlString
&&&&&&&& *&&&&&&&&&&& xml字符串
&&&&&&&& * @param className
&&&&&&&& *&&&&&&&&&&& 类得全称(包名+类名)字符串
&&& @param& cl
&&&&&&&& *&&&&&&&&&&& 对象的class名称
&&&&&&&& * @return 转化成的对象
&&&&&&&& */
&&&&&&&& public Object xmlString2Object(String xmlString ,String className,Class cl) {
&&&&&&&& && // 创建一个读取xml文件的流
&&&&&&&& && StringReader xmlReader = new StringReader(xmlString);
&&&&&&&& && // 创建一个BeanReader实例,相当于转化器
&&&&&&&& && BeanReader beanReader = new BeanReader();
&&&&&&&& && //配置BeanReader实例&
&&&&&& beanReader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);&
&&&&&& beanReader.getBindingConfiguration().setMapIDs(false); //不自动生成ID&
&&&&&& //注册要转换对象的类,并指定根节点名称&
&&&&&& try {
&&&&&&&&&&&&&&&&&& //beanReader.registerBeanClass("SelectUserIDListBean", SelectUserIDListBean.class);
&&&&&&&&&&&&&&&&&& beanReader.registerBeanClass(className,cl);
&&&&&&&& } catch (IntrospectionException e1) {
&&&&&&&&&&&&&&&&&& // TODO Auto-generated catch block
&&&&&&&&&&&&&&&&&& e1.printStackTrace();
&&&&&&&& }&
&&&&&&&& && // 将XML解析Java Object
&&&&&&&& && Object obj =
&&&&&&&& && try {
&&&&&&&& &&& obj = beanReader.parse(xmlReader);
&&&&&&&& && } catch (IOException e) {
&&&&&&&& &&& e.printStackTrace();
&&&&&&&& && } catch (SAXException e) {
&&&&&&&& &&& e.printStackTrace();
&&&&&&&& && }
&&&&&&&& &&
&&&&&&&& }
&&&&&&&& /**
&&&&&&&& * 将对象转换为xml字符串
&&&&&&&& */
&&&&&&&& public String Object2XmlString(Object object) {
&&&&&&&& && String xmlString =
&&&&&&&& && // 创建一个输出流,将用来输出Java转换的XML文件
&&&&&&&& && StringWriter outputWriter = new StringWriter();
&&&&&&&& && // 输出XML的文件头
&&&&&&&& && outputWriter.write("&?xml version='1.0' ?&\n");
&&&&&&&& && // 创建一个BeanWriter实例,并将BeanWriter的输出重定向到指定的输出流
&&&&&&&& && BeanWriter beanWriter = new BeanWriter(outputWriter);
&&&&&&&& && // 配置BeanWriter对象
&&&&&&&& && beanWriter.getXMLIntrospector().getConfiguration()
&&&&&&&& &&&& .setAttributesForPrimitives(false);
&&&&&&&& && beanWriter.getBindingConfiguration().setMapIDs(false);
&&&&&&&& && beanWriter.setWriteEmptyElements(false);
&&&&&&&& && try {
&&&&&&&& &&& beanWriter.write(object);
&&&&&&&& && } catch (Exception e) {
&&&&&&&& &&& e.printStackTrace();
&&&&&&&& && }
&&&&&&&& && xmlString = outputWriter.toString();
&&&&&&&& && // 关闭输出流
&&&&&&&& && try {
&&&&&&&& &&& outputWriter.close();
&&&&&&&& && } catch (IOException e) {
&&&&&&&& &&& e.printStackTrace();
&&&&&&&& && }
&&&&&&&& && return xmlS
&&&&&&&& }
阅读(7655)|
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
历史上的今天
在LOFTER的更多文章
loftPermalink:'',
id:'fks_',
blogTitle:'JavaBean与XML之间的转换',
blogAbstract:'
Myeclipse+jdk1.5以上版本自带JAXB工具(xml',
blogTag:'javabean,xml,转换',
blogUrl:'blog/static/',
isPublished:1,
istop:false,
modifyTime:0,
publishTime:3,
permalink:'blog/static/',
commentCount:0,
mainCommentCount:0,
recommendCount:0,
bsrk:-100,
publisherId:0,
recomBlogHome:false,
currentRecomBlog:false,
attachmentsFileIds:[],
groupInfo:{},
friendstatus:'none',
followstatus:'unFollow',
pubSucc:'',
visitorProvince:'',
visitorCity:'',
visitorNewUser:false,
postAddInfo:{},
mset:'000',
remindgoodnightblog:false,
isBlackVisitor:false,
isShowYodaoAd:false,
hostIntro:'',
hmcon:'1',
selfRecomBlogCount:'0',
lofter_single:''
{list a as x}
{if x.moveFrom=='wap'}
{elseif x.moveFrom=='iphone'}
{elseif x.moveFrom=='android'}
{elseif x.moveFrom=='mobile'}
${a.selfIntro|escape}{if great260}${suplement}{/if}
{list a as x}
推荐过这篇日志的人:
{list a as x}
{if !!b&&b.length>0}
他们还推荐了:
{list b as y}
转载记录:
{list d as x}
{list a as x}
{list a as x}
{list a as x}
{list a as x}
{if x_index>4}{break}{/if}
${fn2(x.publishTime,'yyyy-MM-dd HH:mm:ss')}
{list a as x}
{if !!(blogDetail.preBlogPermalink)}
{if !!(blogDetail.nextBlogPermalink)}
{list a as x}
{if defined('newslist')&&newslist.length>0}
{list newslist as x}
{if x_index>7}{break}{/if}
{list a as x}
{var first_option =}
{list x.voteDetailList as voteToOption}
{if voteToOption==1}
{if first_option==false},{/if}&&“${b[voteToOption_index]}”&&
{if (x.role!="-1") },“我是${c[x.role]}”&&{/if}
&&&&&&&&${fn1(x.voteTime)}
{if x.userName==''}{/if}
网易公司版权所有&&
{list x.l as y}
{if defined('wl')}
{list wl as x}{/list}13024人阅读
最近在项目中遇到了JAVA bean 和XML互转的需求, 本来准备循规蹈矩使用dom4j忽然想起来之前曾接触过的XStream, 一番研究豁然开朗,利器啊利器, 下来就XStream的一些用法与大家分享。
XStream是大名鼎鼎的thought works下的一个开源项目, 主要功能是提供JAVA bean 和XML文本之间的转换,另外还提供JAVA bean和JSON之间的转换,这个不在本次讨论的范围内。
XStream进行转换是非常简单的,对JAVA bean没有任何要求:
不要求对private属性提供access方法(set/get)。不要求提供默认构造函数。
实际的代码操作就更简单了,在JAVA1.5以后XSteam也支持了annotation。 这时就只要在JAVA BEAN中添加若干annotation就可以了,当然如果不允许修改JAVA bean, 那XStream也提供register的方式,也是很简单的。 我准备在例子中体现一下的topic:
基本转换对象起别名处理属性处理List忽略field
1. 基本转换
这是一个普通的JAVA bean:
package xstreamT
public class Person {
public int getAge() {
public void setAge(int age) {
this.age =
public void setName(String name) {
this.name =
public String getName() {
return this.
}转换代码是这样的:
XStream xstream = new XStream();
Person person = new Person();
person.setName(&pli&);
person.setAge(18);
System.out.println(xstream.toXML(person));我们得到了这样的结果:
&xstreamTest.Person&
&name&pli&/name&
&age&18&/age&
&/xstreamTest.Person&
有没有觉得很奇怪为什么会有“xstreamTest.Person”的标签?对照下上面提到的JAVA bean这个标签是来自于JAVA bean的类全路径的。
可是这个并不是我想要的啊,有没办法改变?有,简单吗? 简单!
家丁我们希望将“xstreamTest.Person” 这个莫名其妙的element标签改为“person”我们应该这么做。
package xstreamT
@XStreamAlias(&person&)
public class Person {
public int getAge() {
public void setAge(int age) {
this.age =
public void setName(String name) {
this.name =
public String getName() {
return this.
}而执行代码会变成这样:
XStream xstream = new XStream();
xstream.autodetectAnnotations(true);
Person person = new Person();
person.setName(&pli&);
person.setAge(18);
System.out.println(xstream.toXML(person));
这样我们就得到了想要的:
&name&pli&/name&
&age&18&/age&
这里要提到的是“xstream.autodetectAnnotations(true);” 这句代码告诉XStream去解析JAVA bean中的annotation。这句代码有一个隐患,会在后面讨论。
别名可以改变任何你想在序列化时改变的对象名字,类,属性甚至包名,所用到的其实就是“XSstreamAlias”这个annotation。
3. 处理属性
如果想要将JAVA bean中的“age”属性作为XML中person标签的一个attribute该怎么办呢。
这里介绍另外一个annotation:@XStreamAsAttribute, 我们的JAVA bean变成了这样:
@XStreamAlias(&person&)
public class Person {
@XStreamAsAttribute
public int getAge() {
public void setAge(int age) {
this.age =
public void setName(String name) {
this.name =
public String getName() {
return this.
结果是这样的:
&person age=&18&&
&name&pli&/name&
&/person&好玩吧。
4. 处理List
如果JAVA bean中有List是什么情形呢。
@XStreamAlias(&person&)
public class Person {
@XStreamAsAttribute
List&String& girlF
public List&String& getGirlFriends() {
return girlF
public void setGirlFriends(List&String& girlFriends) {
this.girlFriends = girlF
public int getAge() {
public void setAge(int age) {
this.age =
public void setName(String name) {
this.name =
public String getName() {
return this.
直接转换我们会得到这样的结果:
&person age=&18&&
&name&pli&/name&
&girlFriends&
&string&YuanYuanGao&/string&
&string&QiShu&/string&
&string&BoZhiZhang&/string&
&/girlFriends&
&/person&结果其实也不赖,XStream在这里提供了一个@XStreamImplicit(itemFieldName=***)的annotation来满足用户想将List的根节点去掉和改变列表名字的需求,对应到我们的例子上就是去掉&girlFriends&标签和改变&&string&&.我们来看看效果。
@XStreamAlias(&person&)
public class Person {
@XStreamAsAttribute
@XStreamImplicit(itemFieldName=&girl&)
List&String& girlF
public List&String& getGirlFriends() {
return girlF
public void setGirlFriends(List&String& girlFriends) {
this.girlFriends = girlF
public int getAge() {
public void setAge(int age) {
this.age =
public void setName(String name) {
this.name =
public String getName() {
return this.
结果是这样:
&person age=&18&&
&name&pli&/name&
&girl&YuanYuanGao&/girl&
&girl&QiShu&/girl&
&girl&BoZhiZhang&/girl&
5. 忽略属性
如果在JAVA bean中有些属性不想被序列化,XStream提供了解决这个需求的annotation: @XStreamOmitField
比如说不想讲girlfriends这个List序列化
@XStreamAlias(&person&)
public class Person {
@XStreamAsAttribute
@XStreamImplicit(itemFieldName=&girl&)
@XStreamOmitField
List&String& girlF
public List&String& getGirlFriends() {
return girlF
public void setGirlFriends(List&String& girlFriends) {
this.girlFriends = girlF
public int getAge() {
public void setAge(int age) {
this.age =
public void setName(String name) {
this.name =
public String getName() {
return this.
结果是这样:
&person age=&18&&
&name&pli&/name&
6. Converter
Converter这个是属于XStream中的高级特性了,用于基本功能不能满足的情况下让客户自己定制序列化/反系列化的细节,我们还是通过一个例子进行说明。
假如我要往JAVA bean中添加一个类型为Date的属性:
@XStreamAlias(&person&)
public class Person {
@XStreamAsAttribute
@XStreamImplicit(itemFieldName=&girl&)
@XStreamOmitField
List&String& girlF
public Date getBirthday() {
public void setBirthday(Date birthday) {
this.birthday =
public List&String& getGirlFriends() {
return girlF
public void setGirlFriends(List&String& girlFriends) {
this.girlFriends = girlF
public int getAge() {
public void setAge(int age) {
this.age =
public void setName(String name) {
this.name =
public String getName() {
return this.
看看直接序列化的结果:
&person age=&18&&
&name&pli&/name&
&birthday& 04:35:01.857 UTC&/birthday&
还不错,但是生日只需要年月日就行了,没必要精确到毫秒,这怎么办呢,只能使用converter,我们这是就需要写代码了。
public class DateConverter implements Converter {
public boolean canConvert(Class clazz) {
return (Date.class).equals(clazz);
public void marshal(Object object, HierarchicalStreamWriter writer,
MarshallingContext context) {
Date date = (Date)
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
SimpleDateFormat format = new SimpleDateFormat(&yyyy-mm-dd&);
writer.setValue(format.format(calendar.getTime()));
public Object unmarshal(HierarchicalStreamReader arg0,
UnmarshallingContext arg1) {
稍微解释下这段代码:DateConverter 实现了借口Converter,实现了接口中的三个方法:
public boolean canConvert(Class clazz) 用来检测本converter是否能够转换输入的类型。public void marshal(Object object, HierarchicalStreamWriter writer,MarshallingContext context) 序列化的方法(JAVA bean --& XML)public Object unmarshal(HierarchicalStreamReader arg0,&UnmarshallingContext arg1) 反序列化的方法。因为本例用不到所以没有实现。
此时我们的JAVA bean也要相应改变:
@XStreamAlias(&person&)
public class Person {
@XStreamAsAttribute
@XStreamImplicit(itemFieldName=&girl&)
@XStreamOmitField
List&String& girlF
@XStreamConverter(value=DateConverter.class)
public Date getBirthday() {
public void setBirthday(Date birthday) {
this.birthday =
public List&String& getGirlFriends() {
return girlF
public void setGirlFriends(List&String& girlFriends) {
this.girlFriends = girlF
public int getAge() {
public void setAge(int age) {
this.age =
public void setName(String name) {
this.name =
public String getName() {
return this.
看看结果:
&person age=&18&&
&name&pli&/name&
&birthday&&/birthday&
另外在这里简单说说converter的原理:
其实XStream转换过程就是执行一个个converter的过程,只不过使用的大部分converter都是内建好的,XStream遇到一个待转换的object首先去查找能够转换这个object的转换器(converter)怎么找呢,就是通过converter的canConvert(Class clazz)这个方法,返回为true就是可以转换。明白了吧。
XStream的限制:
Xstream已经是很不错的东西了,如果真要找不足,我发现有两点。
1. 反序列化的时候无法使用autodetectAnnotations()方法通知XStream对象去识别annotation。
还记的前面代码中xstream.autodetectAnnotations(true); 吗, 这句代码的意思是告诉XStream对象需要自动识别annotation, 这在序列化(JAVA bean--&XML)的时候没什么问题。但是在反序列化的时候就有问题了,原因官网上说的比较模糊,总之就是不行,只能通过xstream.processAnnotations(Class clazz) 来显式的注册需要使用annotation的类才行,如果JAVA bean很多就会比较麻烦。但一般来说JAVA bean在代码组织结构中都比较集中,如放在听一个package下,这样也好办,可以再程序中将该package下的JAVA
bean都获取,然后使用xstream.processAnnotations(Class[] clazzs) 批量注册。
2. Null 属性无法被序列化。
之前举的例子JAVA bean中的属性都是被初始化以后才进行序列化的,如果没有初始化就进行序列化会怎样呢 ,还是举个例子
@XStreamAlias(&person&)
public class Person {
private String name = &pli&;
@XStreamAsAttribute
private int age = 19;
@XStreamImplicit(itemFieldName=&girl&)
@XStreamOmitField
List&String& girlF
@XStreamConverter(value=DateConverter.class)
Date birthday = new Date();
public Date getBirthday() {
public void setBirthday(Date birthday) {
this.birthday =
public List&String& getGirlFriends() {
return girlF
public void setGirlFriends(List&String& girlFriends) {
this.girlFriends = girlF
public int getAge() {
public void setAge(int age) {
this.age =
public void setName(String name) {
this.name =
public String getName() {
return this.
我想将其它属性都进行了初始化但是没有将girlFriends这个属性初始化,即使说girlFriends==null. 序列化以后会怎样呢?
&person age=&18&&
&name&pli&/name&
&birthday&&/birthday&
&/person&girlFriends这个属性压根就没有被序列化,其实我是想让它序列化成这个样子:
&person age=&18&&
&name&pli&/name&
&birthday&&/birthday&
&girlFriends/&
有什么办法没,真没啥办法。我查了查源码,确实如果某个属性为null的话就不进行序列化的,唯一的办法是修改源码,这个太费事,如果你有兴趣请参看这个链接上的文章,会有帮助:
另外提一点,XStream也提供了不适用annotation的方式,有兴趣请在XStream的官网上查看。
好了,写的够多了,都比较浅显,有什么疑问请告之。
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:63820次
排名:千里之外
原创:25篇
评论:23条
(1)(1)(2)(1)(1)(1)(1)(4)(2)(2)(2)(1)(2)(1)(3)(1)

我要回帖

更多关于 javabean转xml 的文章

 

随机推荐