开始使用JSON lib——先后台交互

1. json-lib是一个java类库,提供将Java对象,包括beans, maps, collections, java arrays and XML等转换成JSON,或者反向转换的功能。java

2. json-lib 主页 : http://json-lib.sourceforge.net/json

    find-jar(用来查找jar包):http://www.findjar.com/index.x数组

3.执行环境app

     须要如下类库支持测试

  • jakarta commons-lang 2.5
  • jakarta commons-beanutils 1.8.0
  • jakarta commons-collections 3.2.1
  • jakarta commons-logging 1.1.1
  • ezmorph 1.0.6

4.测试this

package com.bipaas.utility;.net

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;code

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;对象

public class TransJSON {blog

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //List集合转换成json代码
        List list = new ArrayList();
        list.add("first");
        list.add("second");
        JSONArray json1 = JSONArray.fromObject(list);
        System.out.println(json1+"………………json1");
       
        //Map集合转换成json代码
        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 json2 = JSONObject.fromObject(map);
        System.out.println(json2+"………………json2");
       
        //Bean转换成json代码
//        JSONObject jsonObject = JSONObject.fromObject(new JSONBean());
       
        //数组转换成json代码
        boolean[] boolArray = new boolean[]{true,false,true};
        JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
        System.out.println(jsonArray1+"………………jsonArray1");
       
        String json = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}"; 
        JSONObject json3 = JSONObject.fromObject( json ); 
        System.out.println(json3+"………………json3");
       
        String json4 = "{bool:true,integer:1,string:\"json\"}"; 
        JSONObject jsonObject3 = JSONObject.fromObject( json4 );
        System.out.println(json4+"………………json4");
       
        //通常数据转换成json代码
        JSONArray jsonArray2 = JSONArray.fromObject("['json','is','easy']");
        System.out.println(jsonArray2+"………………jsonArray2");
       
       
       

    }

}

5.执行结果

log4j:ERROR No appender named [console] could be found. ["first","second"]………………json1 {"arr":["a","b"],"int":1,"name":"json","func":function(i){return this.arr[i];},"bool":true}………………json2 [true,false,true]………………jsonArray1 {"name":"json","bool":true,"int":1,"double":2.2,"func":function(a){ return a; },"array":[1,2]}………………json3 {bool:true,integer:1,string:"json"}………………json4 ["json","is","easy"]………………jsonArray2

相关文章
相关标签/搜索