posts - 122,  comments - 25,  trackbacks - 0
XML/JSON的操作类库,codehaus的xstream,很简单的在xml/json和java对象间转换。

1、所需jar包:xstream-[version].jarxpp3-[version].jar 。xpp3不是必须的,也可以用标准的JAXP DOM parser 来代替,如:
XStream xstream = new XStream(new DomDriver()); // does not require XPP3 library

另外,通过alias可实现xml属性的支持。更多功能,请参阅 Tutorial

2、XML转换代码片段:
Class 转换为 xml 的代码片段:
XStream xstream = new XStream();
xstream.alias("person", Person.class);
xstream.alias("phonenumber", PhoneNumber.class);
Person joe = new Person("Joe""Walnes");
joe.setPhone(
new PhoneNumber(123"1234-456"));
joe.setFax(
new PhoneNumber(123"9999-999"));
String xml 
= xstream.toXML(joe);

The resulting XML looks like this:
<person>
  
<firstname>Joe</firstname>
  
<lastname>Walnes</lastname>
  
<phone>
    
<code>123</code>
    
<number>1234-456</number>
  
</phone>
  
<fax>
    
<code>123</code>
    
<number>9999-999</number>
  
</fax>
</person>

xml转换为java类的代码片段:
Person newJoe = (Person)xstream.fromXML(xml);

3、JSON
另需jar包:jettison.jar 、stax-api.jar。JSON Turorial

Write to json:

package org.sensatic.json.test;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;

public class WriteTest {
    
public static void main(String[] args) {
        Product product 
= new Product("Banana""123"23.00);
        XStream xstream 
= new XStream(new JettisonMappedXmlDriver());
        xstream.alias(
"product", Product.class);
        System.out.println(xstream.toXML(product));    
    }
}

Read from json:
package org.sensatic.json.test;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;

public class ReadTest {
    
public static void main(String[] args) {
        String json 
= "{\"product\":{\"name\":\"Banana\",\"id\":\"123\""
            
+ ",\"price\":\"23.0\"}}";
            
        XStream xstream 
= new XStream(new JettisonMappedXmlDriver());
        xstream.alias(
"product", Product.class);
        Product product 
= (Product)xstream.fromXML(json);
        System.out.println(product.getName());
    }
}

And that's how simple XStream is!
posted on 2008-01-15 10:11 josson 阅读(917) 评论(0)  编辑  收藏 所属分类: java 开发

只有注册用户登录后才能发表评论。


网站导航:
 
<2008年1月>
303112345
6789101112
13141516171819
20212223242526
272829303112
3456789

常用链接

留言簿(3)

随笔分类

随笔档案

收藏夹

搜索

  •  

最新评论

阅读排行榜

评论排行榜