JSON, JQuery 相关资料

来源:互联网 发布:韩国消费水平知乎 编辑:程序博客网 时间:2024/05/18 02:06

首先声明,这篇文章基本属于翻译的东西,如果你对原文感兴趣的话可以访问[url]http://json-lib.sourceforge.net/[/url]这个网址,上面很详细,本人只是断章取义,快速应用这个东东而已.

 
         最近做项目,前台要使用jquery+json来实现 js部分的编码,json就不多说了,目前很流行的ajax调用方式,本文关注的是:如何将javabean转化成json的数据格式。总所周知,json的数据格式如下所示:
        {"name":"huqilong","age":18,"province":"henan"}.................
如果总是拿字符串来拼凑,就会成为一件很恶心的事情,于是google一下,找到了这个东西"Json-Lib".
        一:安装,在刚才的那个网址下载下来json-lib.jar ,添加到你的工程下即可(注意它有几个依赖包,还好都是常用的jar包)。、
       二:使用 JSONArray
 JSONArray的静态方法fromObject()可以直接将java的Array 或者Collection类型转换成Json数据格式,如下:
     boolean[] boolArray = new boolean[]{true,false,true};   
  1. JSONArray jsonArray = JSONArray.fromObject( boolArray );   
  2. System.out.println( jsonArray );   
  3. // prints [true,false,true]  

  1. List list = new ArrayList();   
  2. list.add( "first" );   

  1. list.add( "second" );   
  2. JSONArray jsonArray = JSONArray.fromObject( list );   
  3. System.out.println( jsonArray );   
  4. // prints ["first","second"]  
  1. JSONArray jsonArray = JSONArray.fromObject( "['json','is','easy']" );   
  2. System.out.println( jsonArray );   
  3. // prints ["json","is","easy"]  
     三:将javaBean和HashMap转化成Json对象
            MAP
            Map map = new HashMap();   
            map.put( "name""json" );   
            map.put( "bool", Boolean.TRUE );   
            map.put( "int"new Integer(1) );   
            map.put( "arr"new String[]{"a","b"} );   
            map.put( "func""function(i){ return this.arr[i]; }" );   
  
           JSONObject jsonObject = JSONObject.fromObject( map );   
           System.out.println( jsonObject );   
           // prints ["name":"json","bool":true,"int":1,"arr":["a","b"],"func":function(i)  { return this.arr[i]; }]  
  
       JAVABEAN

  1. class MyBean{   
  2.    private String name = "json";   

  1.    private int pojoId = 1;   
  2.    private char[] options = new char[]{'a','f'};   
  3.    private String func1 = "function(i){ return this.options[i]; }";   
  4.    private JSONFunction func2 = new JSONFunction(new String[]{"i"},"return this.options[i];");   
  5.   
  6.    // getters & setters   
  7.    ...   
  8. }   
  9.   
  10. JSONObject jsonObject = JSONObject.fromObject( new MyBean() );   
  11. System.out.println( jsonObject );   
  12. /* prints  
  13.   {"name":"json","pojoId":1,"options":["a","f"],  
  14.   "func1":function(i){ return this.options[i];},  
  15.   "func2":function(i){ return this.options[i];}}  
  16. */  
 
 
当然还有从json对象转到java对象,从xml转到json,从json转到xml这几种转化,也十分简单,感兴趣的话可以直接看这篇文章里的例子:
原创粉丝点击