json-lib使用

来源:互联网 发布:淘宝达人发布帖子 编辑:程序博客网 时间:2024/06/08 08:08
  1. public class JsonUtil {     
  2.    /**   
  3.     * 从一个JSON 对象字符格式中得到一个java对象 说明:Bean的无参构造函数一定要写, 否则会报:   
  4.     * net.sf.json.JSONException: java.lang.NoSuchMethodException   
  5.     *    
  6.     * @param jsonString   
  7.     * @param pojoCalss   
  8.     * @return   
  9.     */    
  10.    public static Object getObjectFromJsonString(String jsonString,     
  11.            Class pojoCalss) {     
  12.        Object pojo;     
  13.        JSONObject jsonObject = JSONObject.fromObject(jsonString);     
  14.        pojo = JSONObject.toBean(jsonObject, pojoCalss);     
  15.        return pojo;     
  16.    }     
  17.    
  18.    /**   
  19.     * 将java对象转换成json字符串   
  20.     *    
  21.     * @param javaObj   
  22.     * @return   
  23.     */    
  24.    public static String getJsonStringFromObject(Object javaObj) {     
  25.        JSONObject json;     
  26.        json = JSONObject.fromObject(javaObj);     
  27.        return json.toString();     
  28.    }     
  29.    
  30.    /**   
  31.     * 从json HASH表达式中获取一个map   
  32.     *    
  33.     * @param jsonString   
  34.     * @return   
  35.     */    
  36.    @SuppressWarnings("unchecked")     
  37.    public static Map getMapFromJsonString(String jsonString) {     
  38.        JSONObject jsonObject = JSONObject.fromObject(jsonString);     
  39.        Iterator keyIter = jsonObject.keys();     
  40.        String key;     
  41.        Object value;     
  42.        Map valueMap = new HashMap();     
  43.        while (keyIter.hasNext()) {     
  44.            key = (String) keyIter.next();     
  45.            value = jsonObject.get(key);     
  46.            valueMap.put(key, value);     
  47.        }     
  48.        return valueMap;     
  49.    }     
  50.    
  51.    /**   
  52.     * 从Map对象得到Json字串   
  53.     *    
  54.     * @param map   
  55.     * @return   
  56.     */    
  57.    public static String getJsonStringFromMap(Map map) {     
  58.        JSONObject json = JSONObject.fromObject(map);     
  59.        return json.toString();     
  60.    }     
  61.    
  62.    /**   
  63.     * 从json字串中得到相应java数组   
  64.     *    
  65.     * @param jsonString   
  66.     *            like "[\"李斯\",100]"   
  67.     * @return   
  68.     */    
  69.    public static Object[] getObjectArrayFromJsonString(String jsonString) {     
  70.        JSONArray jsonArray = JSONArray.fromObject(jsonString);     
  71.        return jsonArray.toArray();     
  72.    }     
  73.    
  74.    /**   
  75.     * 将list转换成Array   
  76.     *    
  77.     * @param list   
  78.     * @return   
  79.     */    
  80.    public static Object[] getObjectArrayFromList(List list) {     
  81.        JSONArray jsonArray = JSONArray.fromObject(list);     
  82.        return jsonArray.toArray();     
  83.    }     
  84.    
  85.    /**   
  86.     * 用JSONStringer构造一个JsonString   
  87.     *    
  88.     * @param m   
  89.     * @return   
  90.     */    
  91.    public static String buildJsonString(Map m) {     
  92.        JSONStringer stringer = new JSONStringer();     
  93.        stringer.object();     
  94.        for (Object key : m.keySet()) {     
  95.            stringer.key((String) key)     
  96.                .value((String)m.get(key));     
  97.        }     
  98.        stringer.key("phone");     
  99.        //begin nesting a array     
  100.        stringer.array();     
  101.        stringer.value("13998098000");     
  102.        stringer.value("8765432");     
  103.        //nestring object in array     
  104.        stringer.object();     
  105.        stringer.key("ppcall");     
  106.        stringer.value(53881);      
  107.        stringer.endObject();     
  108.        stringer.value("13990980980");     
  109.        //end nesting a array     
  110.        stringer.endArray();     
  111.             
  112.        stringer.endObject();     
  113.        return stringer.toString();     
  114.    }     
  115.    
  116.    public static void printMap(Map map) {     
  117.        for (Object key : map.keySet()) {     
  118.            System.out.println(key + ":" + map.get(key));     
  119.        }     
  120.    }     
  121.    
  122.    public static void main(String[] args) {     
  123.        Map m = new HashMap() {     
  124.            {     
  125.                put("JSon""HelloWorld");     
  126.                put("Flex""Ok");     
  127.            }     
  128.        };     
  129.        System.out.println(buildJsonString(m));     
  130.        System.out     
  131.                .println(new JSONStringer().object().key("JSON").value(     
  132.                        "Hello, World!").key("Flex").value("OK").endObject()     
  133.                        .toString());     
  134.    }     
  135.     


 文章摘抄自:http://log-cd.iteye.com/blog/469498 

以下为自己添加:

JSON jar依赖:

  1. <dependency>  
  2.     <groupId>net.sf.json-lib</groupId>  
  3.     <artifactId>json-lib</artifactId>  
  4.     <version>2.3</version>  
  5.     <classifier>jdk15</classifier>  
  6. </dependency>  

 

以下由于找不到原文引用,无法提供引用地址

1、转化数组和集合

  1. boolean[] boolArray = new boolean[]{true,false,true};  
  2.   
  3.         JSONArray jsonArray = JSONArray.fromObject(boolArray);  
  4.   
  5.         System.out.println(jsonArray);  

输出:

  1. [true,false,true]  


    

  1. List list = new ArrayList();  
  2.   
  3. list.add(“第一个”);  
  4.   
  5.        list.add(“第二个”);  
  6.   
  7.        JSONArray jsonArray = JSONArray.fromObject(list);  
  8.   
  9.        System.out.println(jsonArray);  

输出:

  1. [“第一个", "第二个"]  

     

  1. JSONArray jsonArray3 = JSONArray.fromObject("['json','is','easy']");  
  2.   
  3.        System.out.println(jsonArray3);  

输出:

  1. ["json", "is", "easy"]  


 

2、    转化对象

   2.1转化Map

  1. Map map = new HashMap();  
  2.   
  3. map.put("name","json");  
  4.   
  5. map.put("bool",Boolean.TRUE);  
  6.   
  7. map.put("int",new Integer(1));  
  8.   
  9. map.put("arr",new String[]{"a","b"});  
  10.   
  11. map.put("func","function(i){return this.arr[i];}");  
  12.   
  13. JSONObject json = JSONObject.fromObject(map);  
  14.   
  15. System.out.println(json);  

输出:

  1. ["name": "json", "bool":true, "int",1, "arr":[ "a", "b"], "func":function(i){return this.arr[i];}]  

 

   2.2转化Bean

        从Beans到JSON:

  1. public class MyBean {  
  2.   
  3.         private String name = "json";  
  4.   
  5.     private int pojoId = 1;  
  6.   
  7.         private String func1 = "function(i){return this.options[i]}";  
  8.   
  9.     private JSONFunction func2 = new JSONFunction(new String[]{"i"},"return this.options[i];");  
  10.   
  11.             //以下为get、set方法...  
  12. }  
  13.   
  14.     MyBean bean = new MyBean();  
  15.   
  16.     JSONObject jsonObject = JSONObject.fromObject(bean);  
  17.   
  18.     System.out.println(jsonObject);  

输出:

  1. {"func1":function(i){return this.options[i]},"pojoId":1,"name":"json","func2":function(i){ return this.options[i]; }  


 

        从JSONBeans

  1. String myjson = "{name=\"json\",bool:true,int:1,double:2.2,function:function(a){return a;},array:[1,2]}";  
  2.   
  3. JSONObject json1 = JSONObject.fromString(myjson);  
  4.   
  5. Object bean1 = JSONObject.toBean(json1);  


 

  2.3由JSON生成XML

  1. JSONObject json = new JSONObject(true);  
  2.   
  3. XMLSerializer xmlSerializer = new XMLSerializer();  
  4.   
  5. String xml = xmlSerializer.write(json);  
  6.   
  7. System.out.println("xml:" + xml);  

输出:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3.     <o null="true"/>  


 

  1. JSONObject json2 = JSONObject.fromObject("{\"name\":\"json\",\"bool\":true,\"int\":1}");  
  2.   
  3. String xml2 = xmlSerializer.write(json2);  
  4.   
  5. System.out.println("xml2:" + xml2);  

输出:

  1. <pre class="html" name="code"><?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <o></pre><pre class="html" name="code">    <bool type="boolean">true</bool></pre><pre class="html" name="code">    <int type="number">1</int></pre><pre class="html" name="code">    <name type="string">json</name></pre><pre class="html" name="code"></o>  
  4.   
  5. </pre>  
  6. <pre></pre>  
  7. <p><br>  
  8.  </p>  
  9. <pre class="java" name="code">JSONArray json3 = JSONArray.fromObject("[1,2,3]");  
  10.   
  11. String xml3 = xmlSerializer.write(json3);  
  12.   
  13. System.out.println("xml3:" + xml3);  
  14.   
  15. </pre>  
  16. <p><span style="font-size:16px">输出:</span></p>  
  17. <pre class="html" name="code"><pre class="html" name="code"><?xml version="1.0" encoding="UTF-8"?>  
  18.   
  19. <a></pre><pre class="html" name="code">    <e type="number">1</e></pre><pre class="html" name="code">    <e type="number">2</e></pre><pre class="html" name="code">    <e type="number">3</e></pre><pre class="html" name="code"></a>  
  20.   
  21. </pre>  
  22. <pre></pre>  
  23. <p><br>  
  24. <br>  
  25. <br>  
  26.  </p>  
  27.   
  28. </pre>  

原创粉丝点击