JSON — Java与JSON数据互转

转换时Bean所要求的:

  • 被转换的Bean必需是public的。
  • Bean被转换的属性一定要有对应的get方法,且一定要是public的。
  • Bean中不能用引用自身的this的属性,否则运行时出现et.sf.json.JSONException: There is a cycle in the hierarchy!异常
  • json-lib包转换时,不能以null为键名,否则运行报net.sf.json.JSONException:java.lang.NullPointerException:JSON keys must not be null nor the 'null' string.
  • json-lib包转换时, 转换成XML元素key的名字要符合XML元素标签的命名规则,否则会报nu.xom.IllegalNameException: NCNames cannot start with the character 25异常

转换时问题:

  • 如果某个Bean中存在存放数组的Map属性,则使用org.json包中的JSONObject直接封装时得不到正确的JSON,要用JSONArray对数组进行封装处理,否则为转换JavaScript中的空的对象{},但能使用json-lib包很好地解决这一问题

两种包的比较:

  • json-lib包比org.json要易使用些,至少没有烦人的JSONExcetipn捕获异常了。
  • json-lib对Bean的支持比org.json要强,特别是对bean中内嵌属性的支持较好。

json-lib依赖包:

  1.   commons-beanutils-1.8.0.jar
  2.   commons-collections-3.2.1.jar
  3.   commons-lang-2.4.jar
  4.   commons-logging-1.1.1.jar
  5.   ezmorph-1.0.6.jar
  6.   json-lib-2.3-jdk15.jar
  7.   xom-1.2.2.jar
  • 实例所用到的三个Bean
Java代码  收藏代码
  1. package bean;  
  2.   
  3. /** 
  4.  * 创建Address实体类的POJO 
  5.  * (C) 2009-9-1, jzj 
  6.  */  
  7. public class Address {  
  8.     private String street;//街道  
  9.     private String city;//城市  
  10.     private int zip;//邮编  
  11.     private String tel;//第一个电话号码  
  12.     private String telTwo;//第二个电话号码  
  13.   
  14.     public Address() {  
  15.     }  
  16.   
  17.     public Address(String street, String city, int zip, String tel, String telTwo) {  
  18.         this.street = street;  
  19.         this.city = city;  
  20.         this.zip = zip;  
  21.         this.tel = tel;  
  22.         this.telTwo = telTwo;  
  23.     }  
  24.           
  25.         //以下是get set 方法  
  26.         ......  
  27. }  
Java代码  收藏代码
  1. package bean;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.HashSet;  
  6. import java.util.List;  
  7. import java.util.Map;  
  8. import java.util.Set;  
  9.   
  10. /** 
  11.  * POJO 定义各种类型的属性,便于测试 
  12.  * (C) 2009-9-7, jzj 
  13.  */  
  14. public class OtherBean {  
  15.     /* 
  16.      * 定义一个整数属性 
  17.      */  
  18.     private int intAttr = 1;  
  19.   
  20.     /* 
  21.      * 定义一个浮点数属性 
  22.      */  
  23.     private float floatAttr = 1.1f;  
  24.   
  25.     /* 
  26.      * 定义一个布尔型属性 
  27.      */  
  28.     private boolean booleanAttr = true;  
  29.   
  30.     /* 
  31.      * 定义一个空的属性 
  32.      */  
  33.     private Address nullAttr = null;  
  34.   
  35.     /* 
  36.      * 定义一个字符属性 
  37.      */  
  38.     private char charAttr = 'j';  
  39.   
  40.     /* 
  41.      * 定义一个包装类整型属性 
  42.      */  
  43.     private Integer intgerAttr = new Integer(2);  
  44.   
  45.     /* 
  46.      * 定义一个字符属性 
  47.      */  
  48.     private String strAttr = "jzj";  
  49.   
  50.     /* 
  51.      * 定义一个引用其他Bean的属性 
  52.      */  
  53.     private Address addrArr = new Address("changde""lixian"72452"541-322-1723",  
  54.             "546-338-1100");  
  55.   
  56.     /* 
  57.      * 定义一个字符数组属性 
  58.      */  
  59.     private String[] strArrAttr = new String[] { "str1""str2" };  
  60.   
  61.     /* 
  62.      * 定义一个字符数组属性 
  63.      */  
  64.     private char[] charArrAttr = new char[] { 'j''s''o''n' };  
  65.   
  66.     /* 
  67.      * 定义一个list集合属性 
  68.      */  
  69.     private List listAttr = new ArrayList();  
  70.   
  71.     /* 
  72.      * 定义一个set集合属性 
  73.      */  
  74.     private Set hasSetAttr = new HashSet();  
  75.   
  76.     /* 
  77.      * 定义一个hashMap为存放数组的map属性,如果用 
  78.      * org.json包转换时则得不到正确有结果json-lib则可以 
  79.      */  
  80.     private Map hashMapAttr = new HashMap();  
  81.   
  82.     /** 
  83.      * 构造器,初始化集合 
  84.      */  
  85.     public OtherBean() {  
  86.         List tempList = new ArrayList();  
  87.         tempList.add("one");  
  88.         tempList.add("two");  
  89.   
  90.         listAttr.add("jiang");  
  91.         listAttr.add(tempList);  
  92.         listAttr.add(new Address("P.O BOX 54534""Seattle, WA"42452"561-832-3180",  
  93.                 "531-133-9098"));  
  94.   
  95.         hasSetAttr.addAll(listAttr);  
  96.   
  97.         hashMapAttr.put("first"new String[][] { { "1""2" }, { "3" } });  
  98.         hashMapAttr.put("second"new String[][] { { "one""two" }, { "three" } });  
  99.     }  
  100.         //以下是get set方法  
  101. ......  
  102. }  
Java代码  收藏代码
  1. package bean;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Date;  
  5. import java.util.HashMap;  
  6. import java.util.HashSet;  
  7. import java.util.List;  
  8. import java.util.Map;  
  9. import java.util.Set;  
  10.   
  11. import net.sf.json.JSONFunction;  
  12.   
  13. /** 
  14.  * POJO 定义各种类型的属性,便于测试 
  15.  * (C) 2009-9-7, jzj 
  16.  */  
  17. public class Bean {  
  18.   
  19.     //其他属性略,在OtherBean的基础上加上了otherBeanAttr属性而已  
  20.         ......  
  21.   
  22.     /* 
  23.      * 定义一个引用复杂实例的属性,这样可以测试属性递归情况 
  24.      * print:以上各属性值 
  25.      */  
  26.     private OtherBean otherBeanAttr = new OtherBean();  
  27.   
  28.         //以下是get set 方法  
  29.         ......  
  30. }  
  • 使用json-lib包进行转换
Java代码  收藏代码
  1. package jsonlib;  
  2.   
  3. import java.io.BufferedOutputStream;  
  4. import java.io.ByteArrayOutputStream;  
  5. import java.io.IOException;  
  6. import java.util.ArrayList;  
  7. import java.util.Date;  
  8. import java.util.LinkedHashMap;  
  9. import java.util.List;  
  10. import java.util.Map;  
  11.   
  12. import junit.framework.TestCase;  
  13. import net.sf.ezmorph.bean.MorphDynaBean;  
  14. import net.sf.json.JSONArray;  
  15. import net.sf.json.JSONFunction;  
  16. import net.sf.json.JSONObject;  
  17. import net.sf.json.JsonConfig;  
  18. import net.sf.json.xml.XMLSerializer;  
  19.   
  20. import org.dom4j.Document;  
  21. import org.dom4j.DocumentException;  
  22. import org.dom4j.DocumentHelper;  
  23. import org.dom4j.io.OutputFormat;  
  24. import org.dom4j.io.XMLWriter;  
  25.   
  26. import bean.Address;  
  27. import bean.Bean;  
  28.   
  29. /** 
  30. * 使用json-lib包进行bean、json、xml的数据转换 
  31. * (C) 2009-9-6,jzj 
  32. */  
  33. public class JSONFormatTest extends TestCase {  
  34.   
  35.     public void testDate2Json() {  
  36.   
  37.         JSONObject jsonObj = JSONObject.fromObject(new Date());  
  38.         // print: {"date":10,"day":4,"hours":2,"minutes":2,  
  39.         //"month":8,"seconds":38,"time":1252519358062,"timezoneOffset":-480,"year":109}  
  40.         System.out.println(jsonObj.toString());       
  41.     }  
  42.       
  43.     public void testArray2Json() {  
  44.   
  45.         JSONArray jsonArr = JSONArray.fromObject(new String[][] { { "one""two" },  
  46.                 { "three""four" } });  
  47.         // print: [["one","two"],["three","four"]]  
  48.         System.out.println(jsonArr.toString());  
  49.   
  50.         //json串转JSONArray  
  51.         JSONArray jsArr = JSONArray.fromObject(jsonArr.toString());  
  52.   
  53.         //从JSONObject读取数据  
  54.         //print: three  
  55.         System.out.println(((JSONArray) jsArr.get(1)).get(0));  
  56.         System.out.println("\n");  
  57.     }  
  58.   
  59.     public void testList2Json() {  
  60.         List list = new ArrayList();  
  61.         list.add(new Integer(1));  
  62.         list.add(new Boolean(true));  
  63.         list.add(new Character('j'));  
  64.         list.add(new char[] { 'j''s''o''n' });  
  65.         list.add(null);  
  66.         list.add("json");  
  67.         list.add(new String[] { "json""-""lib" });  
  68.         list.add(new JSONFunction(new String[] { "i" }, "alert(i)"));  
  69.         list.add(new Address("P.O BOX 54534""Seattle, WA"42452"561-832-3180",  
  70.                 "531-133-9098"));  
  71.         //list转JSONArray  
  72.         JSONArray jsArr = JSONArray.fromObject(list);  
  73.   
  74.         /* 
  75.         * list转JSON串 
  76.         * print: [1,true,"j",["j","s","o","n"],null,"json",["json","-","lib"], 
  77.         * function(i){ alert(i) },{"city":"Seattle, WA","street":"P.O BOX 54534", 
  78.         * "tel":"561-832-3180","telTwo":"531-133-9098","zip":42452}] 
  79.         */  
  80.         System.out.println(jsArr.toString(4));  
  81.         //从JSON串到JSONArray  
  82.         jsArr = JSONArray.fromObject(jsArr.toString());  
  83.         //--从JSONArray里读取  
  84.         //print: json  
  85.         System.out.println(((JSONArray) jsArr.get(6)).get(0));  
  86.         //print: address.city = Seattle, WA  
  87.         System.out.println("address.city = " + ((JSONObject) jsArr.get(8)).get("city"));  
  88.         System.out.println("\n");  
  89.     }  
  90.   
  91.     public void testMap2Json() throws DocumentException {  
  92.         Map map = new LinkedHashMap();  
  93.         map.put("integer"new Integer(1));  
  94.         map.put("boolean"new Boolean(true));  
  95.         map.put("char"new Character('j'));  
  96.         map.put("charArr"new char[] { 'j''s''o''n' });  
  97.         //注:不能以null为键名,否则运行报net.sf.json.JSONException: java.lang.NullPointerException:  
  98.         //JSON keys must not be null nor the 'null' string.  
  99.         map.put("nullAttr"null);  
  100.   
  101.         map.put("str""json");  
  102.         map.put("strArr"new String[] { "json""-""lib" });  
  103.         map.put("jsonFunction"new JSONFunction(new String[] { "i" }, "alert(i)"));  
  104.         map.put("address"new Address("P.O BOX 54534""Seattle, WA"42452,  
  105.                 "561-832-3180""531-133-9098"));  
  106.         //map转JSONArray  
  107.         JSONObject jsObj = JSONObject.fromObject(map);  
  108.   
  109.         /* 
  110.         * map转JSON串 
  111.         *  
  112.         * print:{"integer":1,"boolean":true,"char":"j","charArr":["j","s","o","n"], 
  113.         * "nullAttr":null,"str":"json","strArr":["json","-","lib"],"jsonFunction": 
  114.         * function(i){ alert(i) },"address":{"city":"Seattle, WA","street":"P.O BOX 54534", 
  115.         * "tel":"561-832-3180","telTwo":"531-133-9098","zip":42452}} 
  116.         */  
  117.         System.out.println(jsObj.toString(4));  
  118.         //从JSON串到JSONObject  
  119.         jsObj = JSONObject.fromObject(jsObj.toString());  
  120.   
  121.         //--从JSONObject里读取  
  122.         //print: json  
  123.         System.out.println(jsObj.get("str"));  
  124.         //print: address.city = Seattle, WA  
  125.         System.out.println("address.city = "  
  126.                 + ((JSONObject) jsObj.get("address")).get("city"));  
  127.   
  128.         //--从动态Bean里读取数据,由于不能转换成具体的Bean,感觉没有多大用处  
  129.         MorphDynaBean mdBean = (MorphDynaBean) JSONObject.toBean(jsObj);  
  130.         //print: json  
  131.         System.out.println(mdBean.get("str"));  
  132.         //print: address.city = Seattle, WA  
  133.         System.out.println("address.city = "  
  134.                 + ((MorphDynaBean) mdBean.get("address")).get("city"));  
  135.   
  136.         //--JSONObject转XML  
  137.         XMLSerializer xmlSerial = new XMLSerializer();  
  138.         xmlSerial.setRootName("root");  
  139.   
  140.         /*注:转换成XML元素key的名字要符合XML元素标签的命名规则,否则会报 
  141.         nu.xom.IllegalNameException: NCNames cannot start with the character 25异常 
  142.          
  143.         print:       
  144.             <?xml version="1.0" encoding="UTF-8"?> 
  145.             <root> 
  146.                 <address class="object"> 
  147.                     <city type="string">Seattle, WA</city> 
  148.                     <street type="string">P.O BOX 54534</street> 
  149.                     <tel type="string">561-832-3180</tel> 
  150.                     <telTwo type="string">531-133-9098</telTwo> 
  151.                     <zip type="number">42452</zip> 
  152.                 </address> 
  153.                 <boolean type="boolean">true</boolean> 
  154.                 <char type="string">j</char> 
  155.                 <charArr class="array"> 
  156.                     <e type="string">j</e> 
  157.                     <e type="string">s</e> 
  158.                     <e type="string">o</e> 
  159.                     <e type="string">n</e> 
  160.                 </charArr> 
  161.                 <integer type="number">1</integer> 
  162.                 <jsonFunction type="function" params="i"><![CDATA[alert(i)]]></jsonFunction> 
  163.                 <nullAttr class="object" null="true"/> 
  164.                 <str type="string">json</str> 
  165.                 <strArr class="array"> 
  166.                     <e type="string">json</e> 
  167.                     <e type="string">-</e> 
  168.                     <e type="string">lib</e> 
  169.                 </strArr> 
  170.             </root> 
  171.         */  
  172.         System.out.println(write2XML(DocumentHelper.parseText(xmlSerial.write(jsObj))));  
  173.         System.out.println("\n");  
  174.     }  
  175.   
  176.     public void testBean2Json() throws DocumentException {  
  177.         Bean bean = new Bean();  
  178.         JSONObject jsonObj = JSONObject.fromObject(bean);  
  179.   
  180.         /*print: 
  181.             { 
  182.                 "booleanAttr": true, 
  183.                 "charArrAttr":     [ 
  184.                     "j", 
  185.                     "s", 
  186.                     "o", 
  187.                     "n" 
  188.                 ], 
  189.                 "charAttr": "j", 
  190.                 "floatAttr": 1.1, 
  191.                 "hasSetAttr":     [ 
  192.                     "jiang", 
  193.                             [ 
  194.                         "one", 
  195.                         "two" 
  196.                     ], 
  197.                             { 
  198.                         "city": "Seattle, WA", 
  199.                         "street": "P.O BOX 54534", 
  200.                         "tel": "561-832-3180", 
  201.                         "telTwo": "531-133-9098", 
  202.                         "zip": 42452 
  203.                     } 
  204.                 ], 
  205.                 "hashMapAttr":     { 
  206.                     "first":         [ 
  207.                                     [ 
  208.                             "1", 
  209.                             "2" 
  210.                         ], 
  211.                         ["3"] 
  212.                     ], 
  213.                     "second":         [ 
  214.                                     [ 
  215.                             "one", 
  216.                             "two" 
  217.                         ], 
  218.                         ["three"] 
  219.                     ] 
  220.                 }, 
  221.                 "intAttr": 1, 
  222.                 "intgerAttr": 2, 
  223.                 "jsonFunctionAttr": function(name){ alert(name) }, 
  224.                 "listAttr":     [ 
  225.                     "jiang", 
  226.                             [ 
  227.                         "one", 
  228.                         "two" 
  229.                     ], 
  230.                             { 
  231.                         "city": "Seattle, WA", 
  232.                         "street": "P.O BOX 54534", 
  233.                         "tel": "561-832-3180", 
  234.                         "telTwo": "531-133-9098", 
  235.                         "zip": 42452 
  236.                     } 
  237.                 ], 
  238.                 "nullAttr": null, 
  239.                 "otherBeanAttr":     { 
  240.                     "addrArr":         { 
  241.                         "city": "lixian", 
  242.                         "street": "changde", 
  243.                         "tel": "541-322-1723", 
  244.                         "telTwo": "546-338-1100", 
  245.                         "zip": 72452 
  246.                     }, 
  247.                     "booleanAttr": true, 
  248.                     "charArrAttr":         [ 
  249.                         "j", 
  250.                         "s", 
  251.                         "o", 
  252.                         "n" 
  253.                     ], 
  254.                     "charAttr": "j", 
  255.                     "floatAttr": 1.1, 
  256.                     "hasSetAttr":         [ 
  257.                                     { 
  258.                             "city": "Seattle, WA", 
  259.                             "street": "P.O BOX 54534", 
  260.                             "tel": "561-832-3180", 
  261.                             "telTwo": "531-133-9098", 
  262.                             "zip": 42452 
  263.                         }, 
  264.                                     [ 
  265.                             "one", 
  266.                             "two" 
  267.                         ], 
  268.                         "jiang" 
  269.                     ], 
  270.                     "hashMapAttr":         { 
  271.                         "first":             [ 
  272.                                             [ 
  273.                                 "1", 
  274.                                 "2" 
  275.                             ], 
  276.                             ["3"] 
  277.                         ], 
  278.                         "second":             [ 
  279.                                             [ 
  280.                                 "one", 
  281.                                 "two" 
  282.                             ], 
  283.                             ["three"] 
  284.                         ] 
  285.                     }, 
  286.                     "intAttr": 1, 
  287.                     "intgerAttr": 2, 
  288.                     "listAttr":         [ 
  289.                         "jiang", 
  290.                                     [ 
  291.                             "one", 
  292.                             "two" 
  293.                         ], 
  294.                                     { 
  295.                             "city": "Seattle, WA", 
  296.                             "street": "P.O BOX 54534", 
  297.                             "tel": "561-832-3180", 
  298.                             "telTwo": "531-133-9098", 
  299.                             "zip": 42452 
  300.                         } 
  301.                     ], 
  302.                     "nullAttr": null, 
  303.                     "strArrAttr":         [ 
  304.                         "str1", 
  305.                         "str2" 
  306.                     ], 
  307.                     "strAttr": "jzj" 
  308.                 }, 
  309.                 "strArrAttr":     [ 
  310.                     "str1", 
  311.                     "str2" 
  312.                 ], 
  313.                 "strAttr": "jzj" 
  314.             } 
  315.          */  
  316.         System.out.println(jsonObj.toString(4));  
  317.   
  318.         //json转JSONObject  
  319.         jsonObj = JSONObject.fromObject(jsonObj.toString());  
  320.         //print:Seattle, WA  
  321.         System.out.println(((JSONObject) ((JSONArray) jsonObj.get("hasSetAttr")).get(2))  
  322.                 .get("city"));  
  323.   
  324.         //--JSONObject转Bean  
  325.         bean = (Bean) JSONObject.toBean(jsonObj, Bean.class);  
  326.         //注:如果Bean里的某个属性存有数组,则数组转换成list存放,但如果数组为bean属性时转换后还是数组  
  327.         //print: 1  
  328.         System.out.println(((List) ((List) bean.getHashMapAttr().get("first")).get(0))  
  329.                 .get(0));  
  330.         //print: j  
  331.         System.out.println(((char[]) bean.getCharArrAttr())[0]);  
  332.   
  333.         //--Bean转XML  
  334.         XMLSerializer xmlSerial = new XMLSerializer();  
  335.         //设置根节点名  
  336.         xmlSerial.setRootName("root");  
  337.           
  338.         JsonConfig jc = new JsonConfig();  
  339.         //排除不需要转换的属性,排除otherBeanAttr内部引用属性  
  340.         jc.setExcludes(new String[] { "otherBeanAttr" });  
  341.         jsonObj = JSONObject.fromObject(bean, jc);  
  342.         /* 
  343.          print:      
  344.           
  345.             <?xml version="1.0" encoding="UTF-8"?>             
  346.             <root> 
  347.                 <booleanAttr type="boolean">true</booleanAttr> 
  348.                 <charArrAttr class="array"> 
  349.                     <e type="string">j</e> 
  350.                     <e type="string">s</e> 
  351.                     <e type="string">o</e> 
  352.                     <e type="string">n</e> 
  353.                 </charArrAttr> 
  354.                 <charAttr type="string">j</charAttr> 
  355.                 <floatAttr type="number">1.1</floatAttr> 
  356.                 <hasSetAttr class="array"> 
  357.                     <e type="string">jiang</e> 
  358.                     <e class="array"> 
  359.                         <e type="string">one</e> 
  360.                         <e type="string">two</e> 
  361.                     </e> 
  362.                     <e class="object"> 
  363.                         <city type="string">Seattle, WA</city> 
  364.                         <street type="string">P.O BOX 54534</street> 
  365.                         <tel type="string">561-832-3180</tel> 
  366.                         <telTwo type="string">531-133-9098</telTwo> 
  367.                         <zip type="number">42452</zip> 
  368.                     </e> 
  369.                 </hasSetAttr> 
  370.                 <hashMapAttr class="object"> 
  371.                     <first class="array"> 
  372.                         <e class="array"> 
  373.                             <e type="string">1</e> 
  374.                             <e type="string">2</e> 
  375.                         </e> 
  376.                         <e class="array"> 
  377.                             <e type="string">3</e> 
  378.                         </e> 
  379.                     </first> 
  380.                     <second class="array"> 
  381.                         <e class="array"> 
  382.                             <e type="string">one</e> 
  383.                             <e type="string">two</e> 
  384.                         </e> 
  385.                         <e class="array"> 
  386.                             <e type="string">three</e> 
  387.                         </e> 
  388.                     </second> 
  389.                 </hashMapAttr> 
  390.                 <intAttr type="number">1</intAttr> 
  391.                 <intgerAttr type="number">2</intgerAttr> 
  392.                 <jsonFunctionAttr type="function" params="name"><![CDATA[alert(name)]]></jsonFunctionAttr> 
  393.                 <listAttr class="array"> 
  394.                     <e type="string">jiang</e> 
  395.                     <e class="array"> 
  396.                         <e type="string">one</e> 
  397.                         <e type="string">two</e> 
  398.                     </e> 
  399.                     <e class="object"> 
  400.                         <city type="string">Seattle, WA</city> 
  401.                         <street type="string">P.O BOX 54534</street> 
  402.                         <tel type="string">561-832-3180</tel> 
  403.                         <telTwo type="string">531-133-9098</telTwo> 
  404.                         <zip type="number">42452</zip> 
  405.                     </e> 
  406.                 </listAttr> 
  407.                 <nullAttr class="object" null="true"/> 
  408.                 <strArrAttr class="array"> 
  409.                     <e type="string">str1</e> 
  410.                     <e type="string">str2</e> 
  411.                 </strArrAttr> 
  412.                 <strAttr type="string">jzj</strAttr> 
  413.             </root> 
  414.          */  
  415.         System.out.println(write2XML(DocumentHelper.parseText(xmlSerial.write(jsonObj))));  
  416.     }  
  417.   
  418.     private static String write2XML(Document doc) {  
  419.   
  420.         ByteArrayOutputStream cache = null;  
  421.   
  422.         try {  
  423.             cache = new ByteArrayOutputStream(1024 * 512);  
  424.   
  425.             OutputFormat of = new OutputFormat();  
  426.             of.setIndent(true);  
  427.             of.setIndent(" ");  
  428.             of.setIndentSize(4);  
  429.             of.setNewlines(true);  
  430.             BufferedOutputStream bos = new BufferedOutputStream(cache);  
  431.             XMLWriter xmlWrite = new XMLWriter(bos, of);  
  432.             xmlWrite.write(doc);  
  433.             bos.close();  
  434.             return cache.toString("UTF-8");  
  435.         } catch (IOException e) {  
  436.         }  
  437.         return null;  
  438.     }  
  439. }  
  • 使用org.json进行转换
Java代码  收藏代码
  1. package orgjson;  
  2.   
  3. import java.io.BufferedOutputStream;  
  4. import java.io.ByteArrayOutputStream;  
  5. import java.io.IOException;  
  6. import java.util.ArrayList;  
  7. import java.util.Iterator;  
  8. import java.util.LinkedHashMap;  
  9. import java.util.List;  
  10. import java.util.Map;  
  11.   
  12. import junit.framework.TestCase;  
  13. import net.sf.json.JSONFunction;  
  14.   
  15. import org.dom4j.Document;  
  16. import org.dom4j.DocumentException;  
  17. import org.dom4j.DocumentHelper;  
  18. import org.dom4j.io.OutputFormat;  
  19. import org.dom4j.io.XMLWriter;  
  20. import org.json.JSONArray;  
  21. import org.json.JSONException;  
  22. import org.json.JSONObject;  
  23. import org.json.XML;  
  24.   
  25. import bean.Address;  
  26. import bean.Bean;  
  27.   
  28. /** 
  29. * 使用org.json包进行bean、json、xml的数据转换 
  30. * (C) 2009-9-6,jzj 
  31. */  
  32. public class JSONFormatTest extends TestCase {  
  33.   
  34.     public void testArray2Json() throws JSONException {  
  35.   
  36.         JSONArray jsonArr = new JSONArray(new String[][] { { "one""two" },  
  37.                 { "three""four" } });  
  38.         // print: [["one","two"],["three","four"]]  
  39.         System.out.println(jsonArr.toString());  
  40.   
  41.         //json串转JSONArray  
  42.         JSONArray jsArr = new JSONArray(jsonArr.toString());  
  43.   
  44.         //从JSONObject读取数据  
  45.         //print: three  
  46.         System.out.println(((JSONArray) jsArr.get(1)).get(0));  
  47.         System.out.println("\n");  
  48.     }  
  49.   
  50.     public void testList2Json() throws JSONException {  
  51.         List list = new ArrayList();  
  52.         list.add(new Integer(1));  
  53.         list.add(new Boolean(true));  
  54.         list.add(new Character('j'));  
  55.         list.add(new char[] { 'j''s''o''n' });  
  56.         list.add(null);  
  57.         list.add("json");  
  58.         list.add(new String[] { "json""-""lib" });  
  59.         list.add(new JSONFunction(new String[] { "i" }, "alert(i)"));  
  60.         list.add(new Address("P.O BOX 54534""Seattle, WA"42452"561-832-3180",  
  61.                 "531-133-9098"));  
  62.         //list转JSONArray  
  63.         JSONArray jsArr = new JSONArray(list);  
  64.   
  65.         /* 
  66.         * list转JSON串 
  67.         * print: 
  68.             [ 
  69.                 1, 
  70.                 true, 
  71.                 "j", 
  72.                 [ 
  73.                     "j", 
  74.                     "s", 
  75.                     "o", 
  76.                     "n" 
  77.                 ], 
  78.                 null, 
  79.                 "json", 
  80.                 [ 
  81.                     "json", 
  82.                     "-", 
  83.                     "lib" 
  84.                 ], 
  85.                 "function(i){ alert(i) }", 
  86.                 "bean.Address@1cf8583" 
  87.             ] 
  88.  
  89.         * 注:org.json不支持list中非JSON对象与数组对象外的对象,会直接调用对象的toString方法 
  90.         */  
  91.         System.out.println(jsArr.toString(4));  
  92.         //从JSON串到JSONArray  
  93.         JSONArray jsArr1 = new JSONArray(jsArr.toString());  
  94.   
  95.         //--从JSONArray里读取  
  96.         //print: json  
  97.         System.out.println(((JSONArray) jsArr1.get(6)).get(0));  
  98.   
  99.         //不能正确读取对象的信息 print: address.city = bean.Address@1cf8583  
  100.         System.out.println("address.city = " + jsArr1.get(8));  
  101.         System.out.println("\n");  
  102.     }  
  103.   
  104.     public void testMap2Json() throws JSONException, DocumentException {  
  105.         Map map = new LinkedHashMap();  
  106.         map.put("integer"new Integer(1));  
  107.         map.put("boolean"new Boolean(true));  
  108.         map.put("char"new Character('j'));  
  109.         map.put("charArr"new char[] { 'j''s''o''n' });  
  110.         map.put("null"null);  
  111.         map.put("str""json");  
  112.         map.put("strArr"new String[] { "json""-""lib" });  
  113.         map.put("jsonFunction"new JSONFunction(new String[] { "i" }, "alert(i)"));  
  114.         map.put("address"new Address("P.O BOX 54534""Seattle, WA"42452,  
  115.                 "561-832-3180""531-133-9098"));  
  116.         //map转JSONArray  
  117.         JSONObject jsObj = new JSONObject(map);  
  118.   
  119.         /* 
  120.         * map转JSON串 
  121.         * print: 
  122.         { 
  123.             "address": "bean.Address@1cf8583", 
  124.             "boolean": true, 
  125.             "char": "j", 
  126.             "charArr": [ 
  127.                 "j", 
  128.                 "s", 
  129.                 "o", 
  130.                 "n" 
  131.             ], 
  132.             "integer": 1, 
  133.             "jsonFunction": "function(i){ alert(i) }", 
  134.             "null": null, 
  135.             "str": "json", 
  136.             "strArr": [ 
  137.                 "json", 
  138.                 "-", 
  139.                 "lib" 
  140.             ] 
  141.         } 
  142.         */  
  143.         System.out.println(jsObj.toString(4));  
  144.         //从JSON串到JSONObject  
  145.         jsObj = new JSONObject(jsObj.toString());  
  146.         //--从JSONObject里读取  
  147.         //print: json  
  148.         System.out.println(jsObj.get("str"));  
  149.         //print: address.city = Seattle, WA  
  150.         System.out.println("address.city = " + jsObj.get("address"));  
  151.   
  152.         //--org.json不支持从JSONObject到Bean的转换  
  153.         //MorphDynaBean mdBean = (MorphDynaBean) JSONObject.toBean(jsObj);  
  154.   
  155.         //--JSONObject转XML  
  156.         //print:  
  157.         /* 
  158.             <root> 
  159.                 <null>null</null> 
  160.                 <char>j</char> 
  161.                 <integer>1</integer> 
  162.                 <address>bean.Address@901887</address> 
  163.                 <strArr>json</strArr> 
  164.                 <strArr>-</strArr> 
  165.                 <strArr>lib</strArr> 
  166.                 <charArr>j</charArr> 
  167.                 <charArr>s</charArr> 
  168.                 <charArr>o</charArr> 
  169.                 <charArr>n</charArr> 
  170.                 <jsonFunction>function(i){ alert(i) }</jsonFunction> 
  171.                 <str>json</str> 
  172.                 <boolean>true</boolean> 
  173.             </root> 
  174.          */  
  175.         System.out.println(write2XML(DocumentHelper  
  176.                 .parseText(XML.toString(jsObj, "root"))));  
  177.         System.out.println("\n");  
  178.     }  
  179.   
  180.     /** 
  181.     * 如果某个Bean里含有Map属性,且Map里存放的为数组,此时需要对Map里的数组进一步用 
  182.     * JSONArray包装后才能输出正确结果 
  183.     * @throws JSONException 
  184.     */  
  185.     public void testBeanToJsonStr() throws JSONException {  
  186.         Bean bean = new Bean();  
  187.         JSONObject jsonObj = new JSONObject(bean);  
  188.         try {  
  189.   
  190.             /* 如果不用JSONArray进行包装转换,则不能得到正确结果,其关键原因是:如果Bean的某属性 
  191.             * 所对应的属性类型为Map时,转换Map中的值所对就代码如下: 
  192.             *  } else if (result instanceof Map) { 
  193.             *      map.put(key, new JSONObject((Map)result, includeSuperClass)); 
  194.             * 由于上述代码数组转换成了JSONObject对象了,对应的应该JSONArray 
  195.             */  
  196.             System.out.println(jsonObj.toString(4));  
  197.               
  198.             //--以下是正确作法  
  199.             //得到Bean的Map属性值  
  200.             Map hashMapAttr = bean.getHashMapAttr();  
  201.             //对hashMap属性用JSONArray进行包装  
  202.             Iterator it = hashMapAttr.entrySet().iterator();  
  203.   
  204.             //Bean中hashMap属性值转换成map2JsonObj  
  205.             JSONObject map2JsonObj = new JSONObject();  
  206.             while (it.hasNext()) {  
  207.                 Map.Entry entry = (Map.Entry) it.next();  
  208.                 map2JsonObj.put((String) entry.getKey(), new JSONArray(entry.getValue()));  
  209.             }  
  210.   
  211.             //置换掉Bean中hashMap属性原有的map对象值,置换后hashMap属性的值为JSONObject对象实例,  
  212.             //而JSONObject对象实例存储了原hashMap中所对应值的所有信息  
  213.             jsonObj.put("hashMap", map2JsonObj);  
  214.             System.out.println(jsonObj.toString(4));  
  215.   
  216.             //json转JSONObject  
  217.             jsonObj = new JSONObject(jsonObj.toString());  
  218.             //print:Seattle, WA  
  219.             System.out.println(((JSONObject) ((JSONArray) jsonObj.get("hasSetAttr"))  
  220.                     .get(2)).get("city"));  
  221.   
  222.             //--Bean转XML  
  223.             //print:  
  224.             System.out.println(XML.toString(jsonObj, "root"));  
  225.   
  226.         } catch (JSONException e) {  
  227.             e.printStackTrace();  
  228.         }  
  229.     }  
  230.   
  231.     private static String write2XML(Document doc) {  
  232.   
  233.         ByteArrayOutputStream cache = null;  
  234.   
  235.         try {  
  236.             cache = new ByteArrayOutputStream(1024 * 512);  
  237.   
  238.             OutputFormat of = new OutputFormat();  
  239.             of.setIndent(true);  
  240.             of.setIndent(" ");  
  241.             of.setIndentSize(4);  
  242.             of.setNewlines(true);  
  243.             BufferedOutputStream bos = new BufferedOutputStream(cache);  
  244.             XMLWriter xmlWrite = new XMLWriter(bos, of);  
  245.             xmlWrite.write(doc);  
  246.             bos.close();  
  247.             return cache.toString("UTF-8");  
  248.         } catch (IOException e) {  
  249.         }  
  250.         return null;  
  251.     }  
  252. }  

 

源码请参考《JSON入门与实战详解 —— JavaScript、Java与JSON互转》 附件。

posted @ 2014-03-03 16:05  yangkai_keven  阅读(677)  评论(0编辑  收藏  举报