xStream可以轻易的将Java对象和xml文档相互转换,而且可以修改某个特定的属性和节点名称,而且也支持json的转换;
xStream.autodetectAnnotations(true);//设置自动扫描注解
使用jar文件:
XmlUtil.java
package com.ifly.demo.utils;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class XmlUtil {
// object--->xml
public static String simpleobject2xml(Object obj) {
XStream xStream = new XStream(new DomDriver());
xStream.alias(obj.getClass().getSimpleName(), obj.getClass());
String xml = xStream.toXML(obj);
return xml;
}
// xml--->object
public static Object simplexml2object(String xml, Object obj) {
XStream xStream = new XStream(new DomDriver());
xStream.alias(obj.getClass().getSimpleName(), obj.getClass());
Object reobj = xStream.fromXML(xml);
return reobj;
}
}
XmlUtilTest.java
package com.ifly.demo.test;
import java.util.Date;
import org.junit.Test;
import com.ifly.demo.domain.Person;
import com.ifly.demo.utils.XmlUtil;
public class XmlUtilTest {
@Test
public void testSimpleObject2xml() {
Person person = new Person();
person.setId(1);
person.setName("sillycat");
person.setEmail("test@test.com");
person.setTime(new Date());
String xml = XmlUtil.simpleobject2xml(person);
System.out.println(xml);
}
@Test
public void testSimpleXml2object() {
Person person = new Person();
person.setId(1);
person.setName("sillycat");
person.setEmail("test@test.com");
person.setTime(new Date());
String xml = XmlUtil.simpleobject2xml(person);
Person temp = (Person) XmlUtil.simplexml2object(xml, new Person());
System.out.println(temp);
System.out.println(temp.getName());
System.out.println(temp.getEmail());
System.out.println(temp.getTime());
}
}
testSimpleObject2xml()
结果:
<Person>
<id>1</id>
<name>sillycat</name>
<email>test@test.com</email>
<time>2014-12-10 13:57:00.259 UTC</time>
</Person>
testSimpleXml2object()
结果:
com.ifly.demo.domain.Person@13cd5b5
sillycat
test@test.com
Wed Dec 10 21:58:56 CST 2014
实体类:Person.java
package com.ifly.demo.domain;
import java.util.Date;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
public class Person {
/*
* 变为属性
*/
@XStreamAsAttribute
private int id;
/*
* 忽略
*/
@XStreamOmitField
private String name;
private String email;
private Date time;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
}