基本类型到JSON的转化

一、 总结

JSON对象是一个无序的"名称/值"对的集合它开始于“{”,结束于“}”。每一个属性名和值间用“:”提示,属性间用“,”分隔。一个数组开始于"[",结束于"]",值之间用","分隔。
数组和List转换为JSON用JSONArray.fromObject Map、bean、beans(保存在一个List中转换)转换为JSON用 JSONObject.fromObject
JSONObject.toBean(JSONObject类型,Class类型) // 转换为对象(如自定义类对象,Map对象等)

JSON (JavaScript Object Notation)是一种轻量级的数据交换格式,非常适合于服务器与 JavaScript 的交互. JSON 是 JavaScript 原生格式,这意味着在 JavaScript 中处理 JSON 数据不需要任何特殊的 API 或工具包。Json必需的包(重新导入包后需重启下,因为这个问题浪费了我好长时间 ,需注意)commons-beanutils.jar commons-lang-2.4.jarcommons-logging-1.1.1.jarjson-lib-2.2.3-jdk13.jarezmorph-1.0.6.jarcommons-collections-3.2.1.jar

  

这表示一个user对象,拥有username, age, info, address 等属性。同样也可以用JSON来简单的修改数据,修改上面的例子js 代码

function showJSON() {     
    var user =      
    {      
        "username":"andy",     
        "age":20,     
        "info": { "tel": "123456", "cellphone": "98765"},     
        "address":     
            [     
                {"city":"beijing","postcode":"222333"},     
                {"city":"newyork","postcode":"555666"}     
            ]     
    }             
    user.username = "Tom";     
    alert(user.username);     
}   

易错地方 (注意有无外引号):

    function testJson(){  
           
         var str = { "name": "Violet", "password": "character" }; 
         alert(typeof(str));    
         alert(str.password);   
         alert(obj.toJSONString());      
          var a=50,b="xxx";  
          var arr="{id:"+a+",name:'"+b+"'}";
          var str2 = '{ "name": "Violet", "password": "character" }';       
          alert(typeof(str2)); 
          var obj = eval('(' + str2 + ')');
          alert(typeof(obj));   
          alert(obj.name);    
    }  
      

JSONObject resultJSON = new JSONObject();   
resultJSON.put("param1", 1);  
resultJSON.put("param2", 2);  
resultJSON.put("param3", 3);  
System.out.println(resultJSON);    
//{"param1":1,"param2":2,"param3":3}  

二、Java代码转换成json代码
1.List集合转换成json代码

List list = new ArrayList();list.add( "first" );
list.add( "second" );
JSONArray jsonArray2 = JSONArray.fromObject( list );

2.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  json = JSONObject.fromObject(map);

3.Bean转换成json代码

JSONObject jsonObject = JSONObject.fromObject(new JsonBean());

//当是对象的时候 Student student = new Student(); student.setAge(18); student.setName("zhangsan"); student.setSex("male"); JSONObject jsonObject = JSONObject.fromObject(student); System.out.println(jsonObject);//输出{"age":18,"name":"zhangsan","sex":"male"}
4.数组转换成json代码boolean[] boolArray = new boolean[] { true, false, true };JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
**5.beans转换成json代码 **

 List  userInfosList = new ArrayList();  
 UserInfo u1 = new UserInfo();   u1.setUserId(10000);    u1.setUserName("qqqqq");   u1.setPassword("111111");   
UserInfo u2 = new UserInfo();  
 u2.setUserId(10001);    
u2.setUserName("wwwww");   
 u2.setPassword("222222");   
userInfosList.add(u1);  
 userInfosList.add(u2);   
JSONArray json2=JSONArray.fromObject(userInfosList); Iterator it=**json**2.listIterator();       
 while(it.hasNext())   {
            JSONObject obj=(JSONObject)it.next();            
            UserInfo u=(UserInfo)JSONObject.toBean(obj,UserInfo.class);                   
            System.out.println(u.getPassword());       
 }

6、String转JSON

String listStr = "['apple','orange']";        
JSONArray json = JSONArray.fromObject(listStr);  

三、JSON转List、Map

JSON转List

        String str = "['apple','orange']";  
        JSONArray **json** = JSONArray.fromObject(str);  
        Collection list = JSONArray.toCollection(**json**);  
        for (String s : list) {  
               System.out.println(s);  
        }  

JOSN转Map

        String mapStr = "{'age':30,'name':'Michael','baby':['Lucy','Lily']}";  
        JSONObject **json**3 = JSONObject.fromObject(mapStr);  
        Map map = (Map) JSONObject.toBean(**json**3, Map.class);  
        for (Map.Entry entry : map.entrySet()) {  
            System.out.println(entry.getKey() + " " + entry.getValue());  
        }  

四、遍历JSON数据的两种常用方式

var **json**={"status":1,"info":"u83b7u53d6u6210u529f","data":[{"id":"4","name":"u77f3u5bb6u5e84","information":"u5e02","Region_id":"3","type":"1"}]}  
var data=**json**.data;  
for(i=0;i

var **json**=[{"kl_id":"2","kl_title":"Test date1","kl_content":"Test date2","kl_type":"3","id":"6"},{"kl_id":"2","kl_title":"Test1","kl_content":"Test2","kl_type":"1","id":"9"}]  
    var str = "";  
    for (var one in **json**)  
     {  
        for(var key in **json**[one])  
         {  
             str += **json**[one][key] + ",";  
         }  
     }  
     document.write(str);  
List list = query.list();  
List excList = new ArrayList();  
        if(list!=null && list.size()>0){  
            for (int i = 0; i < list.size(); i++) {  
                Object[] obj = (Object[]) list.get(i);  
                EipAnalysisServiceExc excR=new EipAnalysisServiceExc();  
                excR.setId(Long.parseLong(obj[0].toString()));  
                excR.setServiceName(obj[1]!=null?obj[1].toString():null);  
                  
                excList.add(JSONObject.fromObject(excR).toString());  
            }  
        }  
for (int i = 0; i < excList.size(); i++) {  
    JSONObject jSONObject = JSONObject.fromObject(excList.get(i));  
    EipAnalysisServiceExc exc = JSONObject.toBean(jSONObject, EipAnalysisServiceExc.class);  
        }  

由JSONObject.fromObject(excR)得到JSONObject对象,然后toString传输,再JSONObject.fromObject解析为JSONObject对象
使用JSONObject.toBean(JSONObject类型,Class类型) ,转换为对象(如自定义类对象,Map对象等) 转换为类类型

你可能感兴趣的:(基本类型到JSON的转化)