[ActionScript 3.0] AS 实现JSON转换为XML

 1 package com.fylibs.utils
 2 {
 3     /**
 4      * @author:Frost.Yen
 5      * @E-mail:871979853@qq.com
 6      * @create:2015-12-25 下午3:34:28
 7      *
 8      */
 9     public class JSON2XML
10     {
11         public function JSON2XML()
12         {
13         }
14         /**
15          * 将object对象转换成xml,主要目的是将json格式的数据转换成xml
16          * @param obj 要转换的对象
17          * @param node 节点
18          * return XML
19          */
20         public static function obj2xml(obj:Object, node:String):XML
21         {
22             var xml:XML=new XML(<{node}></{node}>); 
23             switch(typeof(obj)) 
24             {
25                 case "int":
26                 case "uint":
27                 case "number":
28                 case "string":
29                 case "boolean":
30                     return new XML(<{node}>{obj.toString()}</{node}>); 
31             }
32             for(var str:String in obj)
33             {
34                 switch(typeof(obj[str]))
35                 {
36                     case "int": 
37                     case "uint":
38                     case "number":
39                     case "string":
40                     case "boolean":
41                         xml.appendChild(<{str}>{obj[str]}</{str}>)
42                         break;
43                     case "array":
44                     case "object": 
45                         if(obj[str].length){
46                             for each(var item:Object in obj[str])
47                             {
48                                 xml.appendChild(obj2xml(item, str)); 
49                             }  
50                         }else{
51                             if(isNaN(Number(str))){//如果不是数字
52                                 xml.appendChild(obj2xml(obj[str], str));
53                             }else{
54                                 xml.appendChild(obj2xml(obj[str], node));
55                             }
56                             
57                         }
58                         break;
59                 }
60             }
61             return xml;
62         }
63     }
64 }

 

------------------------------------------------------------------ Always put yourself in the other's shoes.If you feel that it hurts you,it probably hurts others,too.------------------------------------------------------------------
posted on 2015-12-30 09:49  晏过留痕  阅读(334)  评论(0编辑  收藏  举报