xStream之xml
1. 把对象进行字符串输出,把字符串作为对象读入 [code="java"] package org.frame.xstream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import org.frame.xstream.dataobject.blog.Entry; import com.thoughtworks.xstream.XStream; public class TestObjectOutputStream { public static void main(String[] args) throws IOException, ClassNotFoundException { XStream xstream = new XStream(); StringWriter someWriter = new StringWriter(); ObjectOutputStream out = xstream.createObjectOutputStream(someWriter); out.writeObject(new Entry("Joe", "Walnes")); out.writeObject(new Entry("Someone", "Else")); out.writeObject("hello"); out.writeInt(12345); out.close(); System.out.println(someWriter.toString()); StringReader someReader = new StringReader(someWriter.toString()); ObjectInputStream in = xstream.createObjectInputStream(someReader); Entry a = (Entry)in.readObject(); Entry b = (Entry)in.readObject(); String h = (String)in.readObject(); int aa = in.readInt(); System.out.println(a.title); System.out.println(a.description); System.out.println(b.title); System.out.println(b.description); System.out.println(h); System.out.println(aa); } } [/code] 2. 把对象序列化到文件,和把文件反序列化为对象 [code="java"] package org.frame.xstream; import java.util.Iterator; import java.util.List; import org.frame.xstream.dataobject.blog.Author; import java.io.File; import com.thoughtworks.xstream.persistence.FilePersistenceStrategy; import com.thoughtworks.xstream.persistence.PersistenceStrategy; import com.thoughtworks.xstream.persistence.XmlArrayList; public class TestPersistence { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub //the E:/tmp must be exists PersistenceStrategy strategy = new FilePersistenceStrategy(new File("E:/tmp")); add(strategy); remove(strategy); } public static void add(PersistenceStrategy strategy ){ // creates the list: List list = new XmlArrayList(strategy); // adds four authors list.add(new Author("joe walnes")); list.add(new Author("joerg schaible")); list.add(new Author("mauro talevi")); list.add(new Author("guilherme silveira")); // adding an extra author Author mistake = new Author("mama"); list.add(mistake); //五个对象会生成五个文件 int@1.xml, int@2.xml, int@3.xml, int@4.xml, int@5.xml //原来xstream生成全名的原因是为了序列化和反序列化. } public static void remove(PersistenceStrategy strategy){ // looks up the list: List list = new XmlArrayList(strategy); // remember the list is still there! the files int@[1-5].xml are still in /tmp! // the list was persisted! for(Iterator it = list.iterator(); it.hasNext(); ) { Author author = (Author) it.next(); if(author.getName().equals("mama")) { System.out.println("Removing mama..."); it.remove(); } else { System.out.println("Keeping " + author.getName()); } } } } [/code] 文件内容如下 [code="java"] mauro talevi [/code] 其实这种方式挺好,比如会员登陆可以生成其登陆的基本信息,需要获取的时候,从文件系统反序列化读取,与数据库类似,但是存储的内容比较少,适合一般的场景,不需要数据库时[当然如果使用这种方式来实现数据库的API也不错啊,有时间研究研究,写测试用例的时候就可以更清晰了] 3. 把json转化为对象,和把对象生成对应的json [code="java"] package org.frame.xstream; import java.io.Writer; import org.frame.xstream.dataobject.blog.Entry; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver; import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver; import com.thoughtworks.xstream.io.json.JsonWriter; /** * 其实使用返回的 { susccess: "true", errorMessage: "你长得太丑了" } * * 可以使用对象形式,也可以建一个vm文件来维护返回的信息,推荐*.vm. 当然使用Action直接返回字符串,比拼凑的好玩点. * * @author yangchunlong.tw * */ public class TestWithJson { /** * @param args */ public static void main(String[] args) { XStream xstream = createByJettison(); jsonToObject(xstream); } public static void createJson(XStream xstream) { Entry product = new Entry("Banana", "123"); xstream.setMode(XStream.NO_REFERENCES); xstream.alias("product", Entry.class); System.out.println(xstream.toXML(product)); // 把xstream使用到json上也是相当给力的. // 这里都有一个对象名,还有一个不要根节点的 } public static void jsonToObject(XStream xstream) { String json = "{\"product\":{\"title\":\"Banana\",\"description\":123}}"; //XStream xstream = new XStream(new JettisonMappedXmlDriver()); xstream.alias("product", Entry.class); Entry product = (Entry) xstream.fromXML(json); System.out.println(product.title); System.out.println(product.description); } public static XStream createByJettison() { return new XStream(new JettisonMappedXmlDriver()); } public static XStream createByJDK() { // 不需要根节点,这个牛B了,不是接口也可以重写方法 return new XStream(new JsonHierarchicalStreamDriver() { public HierarchicalStreamWriter createWriter(Writer writer) { return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE); } }); } } [/code] 4. 把对象转化为xml和把xml转化为对象 [code="java"] package org.frame.xstream; import org.frame.xstream.dataobject.Person; import org.frame.xstream.dataobject.PhoneNumber; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; import com.thoughtworks.xstream.io.xml.StaxDriver; public class TestXStream { public static void main(String[] args) { //声名xstream XStream xstream = createByXPP3(); xstream.alias("person", Person.class); xstream.alias("phonenumber", PhoneNumber.class); //组织对象 Person joe = new Person("Joe", "Walnes"); joe.setPhone(new PhoneNumber(123, "1234-456")); //生成xml String xml = xstream.toXML(joe); System.out.println(xml); Person re = (Person) xstream.fromXML(xml); System.out.println(re.getFirstname()); System.out.println(re.getLastname()); System.out.println(re.getPhone().getCode()); System.out.println(re.getPhone().getNumber()); } /** * XPP3. * * javax.xml.parsers.DocumentBuilderFactory * @return */ public static XStream createByXPP3(){ return new XStream(); } /** * JAXP DOM parser * * javax.xml.parsers.DocumentBuilderFactory * @return */ public static XStream createByDomDrive(){ return new XStream(new DomDriver()); } /** * Java 6 the integrated StAX parser * * * @return */ public static XStream createByStax(){ return new XStream(new StaxDriver()); } } 5. 可以使用xstream高级有功能,使实体与xml名字不对应也能互转 [code="java"] package org.frame.xstream; import org.frame.xstream.dataobject.Person; import org.frame.xstream.dataobject.PhoneNumber; import org.frame.xstream.dataobject.blog.Author; import org.frame.xstream.dataobject.blog.AuthorConverter; import org.frame.xstream.dataobject.blog.Blog; import org.frame.xstream.dataobject.blog.Entry; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; import com.thoughtworks.xstream.io.xml.StaxDriver; public class TestXStreamAlias { 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 = createByXPP3(); // xstream.alias("blog", Blog.class); // xstream.alias("entry", Entry.class);//指定类的别包 // xstream.aliasPackage("org.ycl", "org.frame");//改变包名 xstream.processAnnotations(Blog.class);//启动Blog类的注解 // xstream.useAttributeFor(Blog.class, "writer");//设置节点为属性 xstream.aliasField("author", Blog.class, "writer");//指定类中属性的别名 xstream.processAnnotations(Entry.class);//启动Entry类的注解 //如何把Anthor对象转化为String //xstream.registerConverter(new AuthorConverter()); // xstream.addImplicitCollection(Blog.class, "entries");//不显示集合元素. String xml = xstream.toXML(teamBlog); System.out.println(xml); Blog re = (Blog) xstream.fromXML(xml); System.out.println(re.getContent()); System.out.println(re.writer.getName()); } /** * XPP3. * * javax.xml.parsers.DocumentBuilderFactory * @return */ public static XStream createByXPP3(){ return new XStream(); } /** * JAXP DOM parser * * javax.xml.parsers.DocumentBuilderFactory * @return */ public static XStream createByDomDrive(){ return new XStream(new DomDriver()); } /** * Java 6 the integrated StAX parser * * * @return */ public static XStream createByStax(){ return new XStream(new StaxDriver()); } } [/code] [/code]