XStream实现javabean和xml、json转化

时间:2020-11-27 19:05:42
xStream转换XML、Json数据

xStream可以轻易的将javaBean对象和xml相互转换,修改某个特定的属性和节点名称,而且也支持json的转换。

maven依赖:

1 <dependency>
2     <groupId>com.thoughtworks.xstream</groupId>
3     <artifactId>xstream</artifactId>
4     <version>1.4.5</version>
5 </dependency>

一:javaBean <-> xml

1.基本

 1 class Person {  
 2         private String name; 3 private int phoneNuber; 4 private List<Address> addresses = new ArrayList<Address>(); 5  ... 6 } 7 class Address { 8 private String street; 9 private int houseNo; 10  ... 11 } 12 public static String toXML(){ 13 XStream xStream = new XStream(); 14 xStream.alias("person", Person.class); 15 xStream.alias("address",Address.class); 16  xStream.setMode(XStream.NO_REFERENCES); 17 xStream.addImplicitCollection(Person.class, "addresses");//去除 addresses节点生成 18 xStream.useAttributeFor(Person.class,"name"); //name作为person节点的属性出现,即name=xxx,不设置此项的话,name作为单独的节点<name>出现 19 return xStream.toXML(person); 20  } 21 public static Person toEntity(String inputXML){ 22 XStream xs = new XStream(); 23 xs.alias("person",Person.class); 24 xs.alias("address",Address.class); 25  xs.setMode(XStream.NO_REFERENCES); 26 xs.addImplicitCollection(Person.class,"addresses"); 27 xs.useAttributeFor(Person.class, "name"); 28 Person person = (Person)xs.fromXML(inputXML); 29 return person; 30 } 

 2.基于annotations

//设置Person类在xml中的别名  
@XStreamAlias("person")
class Person {  
         //将name设置为XML person 元素的 attribute  
         @XStreamAsAttribute()
          private String name;  
          private int phoneNuber; 
         //将此字段名在XML中去掉  
          @XStreamImplicit()   
       private List<Address> addresses = newArrayList<Address>();
          ...
  }
  @XStreamAlias("address")
  class Address {  
          private String street;  
          private int houseNo;
         ...
 }

public static Person toEntity(String inputXML){  
        XStream xs = new XStream();    
        xs.setMode(XStream.NO_REFERENCES);    
        //注册使用了注解的bean 
        xs.processAnnotations(new Class[]{Person.class,Address.class});  
        Person person = (Person)xs.fromXML(inputXML);  
        return person;
    }  

 public static String toXML(){  
        XStream xStream = new XStream();  
        xStream.setMode(XStream.NO_REFERENCES);   
        //注册使用了注解的VO  
        xStream.processAnnotations(new Class[]{Person.class,Address.class});  
        return xStream.toXML(person);     
    }  

2.javaBean <-> json

     待完善。。。。。。。。。。。。。