The xStream framework can easily convert Java objects and xml documents to each other,and can modify a specific attribute and node name,and also supports json conversion;they all perfectly support JSON& #xff0c; But the support for xml is not very good yet. Restricts the description of Java objects to a certain extent , Cannot allow xml to fully reflect the description of Java objects. Here we will introduce xStream’s perfect support for JSON and XML. xStream is not only very friendly to XML transformation, but also provides annotation annotation, which can complete the description of xml nodes and attributes in JavaBean. And JSON is also supported , only need to provide the relevant JSONDriver to complete the conversion.
The following is a case to demonstrate how the xStream framework operates xml and json
Step 1:Add jar,As shown below:
Step 2: ;New Student entity class
package com.ljq.test;
import java.io.Serializable;
@SuppressWarnings(“serial”)
public class Student implements Serializable {
private int id;
private String name;
private String email;
private String address;
private String birthday;
public Student() {
}
public Student(int id, String name, String email, String address,
String birthday) {
super();
this.id = id;
this.name = 61;name;
this.email = email;
this.address = address;
this.birthday = birthday;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this .address = address;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = ; birthday;
}
public String toString() {
return this. name + “#” + this.id + “#” + this.address + “#”
+ this.birthday + “#” + this.email;
}
}
SingleValueCalendarConverter
package com.ljq.test;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
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;
/**
* type converter , analog to Calendar Make a conversion
*
* @author jiqinlin
*
*/
public class SingleValueCalendarConverter implements Converter {
public void marshal(Object source, HierarchicalStreamWriter writer,
MarshallingContext context) {
Calendar calendar = (Calendar) source;
writer.setValue(String. valueOf(calendar.getTime().getTime()));
}
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(new Date(Long.parseLong(reader.getValue())) );
return calendar;
}
public boolean canConvert(Class type) {
return type.equals(GregorianCalendar.class);
}
}
Use Annotate to set
package com.ljq.test;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
/**
* Use annotations to set up
*
* @author jiqinlin
*
*/
@SuppressWarnings(“serial”)
public class Classes implements Serializable {
/**
* Set property display
*/
@XStreamAsAttribute
@XStreamAlias(“name”)
private String name;
/**
* ignore
*/
@XStreamOmitField
private int number;
@XStreamImplicit(itemFieldName = “Students”)
private List students;
@SuppressWarnings(“unused”)
@XStreamConverter(SingleValueCalendarConverter.class)
private Calendar created = new GregorianCalendar();
public Classes() {
}
public Classes(String name, Student student, Calendar created) {
super();
this .name = name;
this.students = Arrays.asList(student);
this. created = created;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public List getStudents() {
return span> students;
}
public void setStudents(List students) {
this .students = students;
}
public Calendar getCreated() {
return created;
}
public void setCreated(Calendar created) {
this. created = created;
};
}
Step 3:test
The picture above is the unit test method directory
package com.ljq.test;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StringReader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import span> org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import span> com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
import com.thoughtworks.xstream.io.json.JsonWriter;
/**
* Test code
*
* @author jiqinlin
*
*/
public class XStreamTest {
private XStream xstream=null;
private span> ObjectInputStream inStream=null;
private ObjectOutputStream outStream=null;
private Student student=null;
/**
* initialization
*/
@Before
public void init(){
xstream& #61;new XStream();
student=new Student();
student.setAddress(“china”);
student.setEmail(“416501600@qq.com”);
student.setId(1);
student.setName(“ljq”);
student.setBirthday(” 1988-04-04″);
}
/**
* release resources
*/
@After
public void destroy() {
xstream = null;
student = null;
try {
if (inStream != null) {
inStream.close();
}
if(outStream!& #61;null){
outStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* java object converted to xml object
*/
@Test
public void beanToXml(){
try {
info(“java->xml”);
//
// 1
// ljq
// 416501600@qq.com
// china
// 1988-04-04
//
info(xstream.toXML(student) );
info(“renamed xml”);
//package rename
xstream.aliasPackage(“com”, “com.ljq.test”); // Remember to write the package name com.ljq.test correctly
//
// 1
// ljq
// 416501600@qq. com
// china
// 1988-04-04
//
info(xstream.toXML(student));
//Class Rename
xstream.alias (“Student”, Student.class);
//Property Rename
xstream.aliasField(“birth”, Student.class, “birthday”);
//
// 1
// ljq
// 416501600@qq.com
// china
// 1988-04-04
//
info(xstream.toXML(student));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Convert the List collection object into an xml object
*/
@Test
public void listToXml(){
try{
List students=new ArrayList() ;
students.add(new Student(1, “zhangsan1”, “zhangsan1@126.com”, “china”, “1988-04-04”));
students.add(new Student(2, “zhangsan2”, “zhangsan2@126.com”, “china”, “1988-04-04”));
//id reference
//xstream.setMode(XStream.ID_REFERENCES);
//Class Rename
xstream.alias(“Student”, Student.class );
//Root element rename
xstream.alias(“beans”, List. class);
//Set id and name as attributes of the parent class (Student) element
xstream.useAttributeFor(Student.class, “id”);
xstream.useAttributeFor(Student.class, “name”);
//
//
// zhangsan1@126.com
// “email”: “tom@125.com”,
// “address”: “china”,
// “birthday”: “1988-04-04”
// },
//{
// “id”: 0,
// “name”: “jack”
// }
//]
info(xstream.toXML( list));
}
/**
* Map conversion json
* /
@Test
public void map2JSON() {
xstream = new XStream(new JsonHierarchicalStreamDriver());
//xstream = new XStream(new JettisonMappedXmlDriver());
xstream.alias(“student”, Student.class);
Map map = new HashMap();
map.put(“No.1”, student);
student = ; new Student();
student.setAddress(“china”);
student.setEmail(“tom@125.com”);
student .setId(2);
student.setName(“tom”);
student.setBirthday(“2010-11-21”);
map.put(“No.2”, student);
student = new Student();
student.setName(“jack”);
map.put(” No.3″, student);
// {“map”: [
// [
// “No.1”,
// {
// “id”: 1,
// “name”: “ljq “,
// “email”: “416501600@qq.com”,
// “address”: “china”,
// “birthday”: “1988-04-04”
// }
// ],
/ / [
// “No.3”,
// {
// “id”: 0,
// “name”: “jack”
// }
// ],
// [
// “No.2”,
// {
// “id”: 2,
// “name”: “tom”,
// “email”: “tom& #64;125.com”,
// “address”: “china”,
// “birthday”: “2010-11-21”
// }
/ // ]
// ]}
info(xstream. toXML(map));
info(“———————“);
// Delete root node
xstream = new XStream(new JsonHierarchicalStreamDriver( ) {
public HierarchicalStreamWriter createWriter(Writer out) {
return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE);
}
});
xstream.alias(“student”, Student.class);
// [
// [
// “No .1”,
// {
// “id”: 1 ,
// “name”: “ljq”,
// ” email”: “416501600@qq.com”,
// “address”: “china”,
// “birthday”: “1988-04-04”
// }
// ],
// [
// “No.3”,
// {
// “id”: 0,
// “name”: “jack”
// }
// ],
// [
// “No.2”,
// {
// “id”: 2,
// “name”: “tom” ,
// “email”: “tom@125.com”,
// “address”: “china”,
// “birthday”: “2010-11-21”
// }
// ]
// ]
info(xstream.toXML(map));
}
/* *
* Convert JSON to java object
*
* @throws JSONException
*/
@Test
public void jsonToObject(){
String json =
“{\”student\”: ” +
“{” + “\”id\”: 1,”
+ “\”name\”: \”haha\”,”
+ “\”email\”: \”email\”,”
+ “\ “address\”: \”address\”,”
+ “\”birthday\”: \”2010-11-22\”” + “}”+
“}” +
“}”;
//JsonHierarchicalStreamDriver read JSON string to java object error , ;but JettisonMappedXmlDriver can
xstream = new XStream(new JettisonMappedXmlDriver());
xstream.alias(“student”, Student.class);
info(xstream.fromXML(json).toString());
//JettisonMappedXmlDriver converts the List collection wrong , but JsonHierarchicalStreamDriver can convert correctly
json = “{\”list\” : [“+
“{“+
“\”id\”: 1,”+
“\”name\”: \”ljq \”,”+
“\”email\”: \”416501600@qq.com\”,”+
“\”address\”: \”china \”,”+
“\”birthday\”: \”1988-04-04\””+
“},”+
” {“+
“\”id\”: 2,”+
“\”name\”: \”tom\”,”+
“\”email\”: \”tom@125.com\”,”+
“\”address\”: \”china\”,”+
“\”birthday\”: \”1988-04-04\””+
“},”+
“{“+
“\ “id\”: 0,”+
“\”name\”: \”jack\””+
“}”+
“] }”;
//xstream = new XStream(new JsonHierarchicalStreamDriver()); //will Error
List list = (List) xstream.fromXML(json);
System.out.println(list. size());//0 seems conversion failed
}
public final void info(String string) {
System.out.println(string);
}
public final void error(String string) {
System.err.println(string);
}
}
For details, please visit: tp://www.cnblogs.com/hoojo/archive/2011/04/22/2025197.html
Transfer: https://www.cnblogs.com/linjiqin/archive/2012/02/22/2362764.html
n>// “No.2”,
// {
// “id”: 2,
// “name”: “tom”,
// “email”: “tom@125.com”,
// ” address”: “china”,
// “birthday”: “2010-11-21”
/ / }
// ]
// ]
info(xstream.toXML(map));
}
/**
* Convert JSON to java object
*
* @throws JSONException
*/
@Test
public void jsonToObject(){
String json @ 61;
“{\”student\”: ” +
“{” + “\”id\”: 1,”
+ “\ “name\”: \”haha\”,”
+ “\”email\”: \”email\”,”
+ “\”address\”: \ “address\”,”
+ “\”birthday\”: \”2010-11-22\”” + “}”+
“}” & #43;
“}”;
//JsonHierarchicalStreamDriver read JSON string to java object error , but JettisonMappedXmlDriver can
xstream = new XStream(new JettisonMappedXmlDriver());
xstream.alias(” student”, Student.class);
info(xstream.fromXML(json).toString());
// JettisonMappedXmlDriver conversion List collection error , but JsonHierarchicalStreamDriver can be converted correctly
json = “{\”list\”: [“+ ;
“{“+
“\”id\”: 1,”+
“\”name\”: \”ljq\”,”&# 43;
“\”email\”: \”416501600@qq.com\”,”+
“\”address\”: \”china\”,”&# 43;
“\”birthday\”: \”1988-04-04\””+
“},”+
“{“+
“\”id\”: 2,”+
“\”name\”: \”tom\”,”+
“\”email\” : \”tom@125.com\”,”+
“\”address\”: \”china\”,”+
“\”birthday\” : \”1988-04-04\””+
“},”+
“{“+
“\”id\”: 0 ,”+
“\”name\”: \”jack\””+
“}”+
“]}”;
//xstream = new XStream(new JsonHierarchicalStreamDriver()); //will report an error
List list = (List) xstream.fromXML(json);
System.out.println(list.size());//0 seems to fail to convert
}
public final void info(String string) {
System.out.println(string);
}
public final void error(String string) {
System.err.println(string);
}
}
For details, please see: tp://www.cnblogs.com/hoojo/archive/2011/04/22/2025197.html
Transfer: https ://www.cnblogs.com/linjiqin/archive/2012/02/22/2362764.html