您的位置:首页 > Web前端 > JavaScript

xstream在 xml、json和bean之…

2016-06-08 09:23 477 查看
 

    
  xstream 在xml、json
和bean之间的转化,网上有很多案例,对于常规格式之间的转化都可以轻松实现。最近在解析xml的过程中,遇到了xml节点中有属性值的情 况,一时间搞不定,google一翻,经过尝试,终于解决了这个问题。同时把这种xml转化成bean后,再将bean转化成json时,由于注解写的不规范,也造成了一下困扰,所以在写注解时,写清楚还是很重要的。具体实现过程,主要是bean的注解实现如下:

 

待转化的xml:

         
< table output='table' >

                
< product name='产品一' >

                      
< attribute name='颜色' AttributeType='text'
>红色< /attribute >

                      
< attribute name='价格' AttributeType='image' >30<
/attribute >

               
< /product >

              
< product name='产品二' >

                     
< attribute name='颜色' AttributeType='text' >蓝色< /attribute


                    
< attribute name='价格' AttributeType='image' >50<
/attribute >

         <
/product >

        
< /table >

对应的bean

        
@XStreamAlias("table")

         
public class Table {

 

               
@XStreamImplicit(itemFieldName = "product")

               
private List products;

 

             
@XStreamAsAttribute                         //将output标识为table的属性

             
@XStreamAlias("output")

             
private String output;

       
}   

 

       
 @XStreamAlias("product")

        
public class Product {

 

                 
@XStreamImplicit(itemFieldName = "attribute")

                 
private List attributes;

 

                 
@XStreamAsAttribute

                
@XStreamAlias("name")

                
private String name;

         
}

         

 

      
@XStreamAlias("attribute")

       @XStreamConverter(value=ToAttributedValueConverter.class,
strings={"attribute"})  //将属性值作为节点的内容

       public
class Attribute {

 

                  
@XStreamAsAttribute

                  
@XStreamAlias("name")

                  
private String name;

 

                 
@XStreamAsAttribute

                
 @XStreamAlias("AttributeType")

                 
private String attributeType;

 

                
@XStreamAlias("Attribute")            //xml转化成bean时,该注解不起作用,主要用在json生成上

                
private String attribute;

      
}

 

        此为主要的bean代码,转化过程,直接调用xstream的方法即可,在转化json时,需要注册NullConvert转化器,该转化器继承自Convert,实现过程中,主要运用java
的反射机制,网上有相关的实现。 在解决问题的过程中,新学习了  
@XStreamAsAttribute、@XStreamConverter的使用。

 

 

 

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: