RoyalAjax(三),Java对象的序列化

尽管目前已有很多将POJO序列化的方式,但鉴于将要被序列化的都是Java的简单对象,对生成的XML也不要求验证,完全可以用下面的代码递归生成:

 /**
  * <p>get XML document from an object ,author by Jarez Wu
  * @param o an object
  * @return the XML-encoded String;
  */
 public static String getXMLDescription(Object o){
 String xmlstr="";
    
 if(o instanceof Number||o instanceof String){//do when is leaf of xml tree,here are some translations for javascript gramma
  String str=o.toString();
  str=str.replaceAll("/"","/"");
  str=str.replaceAll("/n","");
  str=str.replaceAll("'","'");
  String ret="<![CDATA["+str+"]]>";
  return ret;
 }
    
 BeanInfo bi=null;
 PropertyDescriptor[] props=null;
 try {
        bi = Introspector.getBeanInfo(o.getClass(),Object.class);
        props = bi.getPropertyDescriptors();
        for(int i=0;i<props.length;i++){
            String propname=props[i].getDisplayName();
            try{
                Object propvalue=props[i].getReadMethod().invoke(o,null);
                if(propvalue.getClass().isArray()){//递归遍历数组
                    try{
                        Object[] arr=(Object[])propvalue;
                        for(int j=0;j<arr.length;j++){
                            xmlstr+="<"+propname+">";
                            xmlstr+=getXMLDescription(arr[j]);
                            xmlstr+="</"+propname+">";
                        }
                    }catch(Exception e){
                    }
                }else if(propvalue instanceof AbstractCollection){//递归遍历迭代
                 Iterator iter=((AbstractCollection)propvalue).iterator();
                 while(iter.hasNext()){
                        xmlstr+="<"+propname+">";
                        xmlstr+=getXMLDescription(iter.next());
                        xmlstr+="</"+propname+">";
                 }
                }else{
                    xmlstr+="<"+propname+">";
                    xmlstr+=getXMLDescription(propvalue);
                    xmlstr+="</"+propname+">";
                }
            }catch(Exception e){}
        }
 }catch(Exception e){
  e.printStackTrace();
 }
 return xmlstr;
 }

这段代码生成的XML如下所示:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值