码迷,mamicode.com
首页 > Web开发 > 详细

不同情景下的json转换

时间:2015-11-11 19:12:20      阅读:287      评论:0      收藏:0      [点我收藏+]

标签:

一、json对象与json字符串互相转换

1.使用原生javascript语法

 json对象=>json字符串

function json2str(o) {
        var arr = []; 
        var fmt = function(s) { 
        if (typeof s == ‘object‘ && s != null) 
            return json2str(s); 
        return /^(string|number)$/.test(typeof s) ? "\"" + s + "\"" : s; 
        } 
        for (var i in o) 
           arr.push("\"" + i + "\":" + fmt(o[i])); 
        return ‘{‘ + arr.join(‘,‘) + ‘}‘; 
    } 

 json字符串=>json对象

var jsonStr=eval("("+jsonObj+")");

2.使用json官方提供的json2.js (注:Firefox,chrome,opera,safari,ie9,ie8等浏览器不必引入,自带支持)

json对象=>json字符串

var jsonStr=JSON.stringify(jsonObj)

json字符串=>json对象

var jsonObj=JSON.parse(jsonStr);

3.使用jQuery提供的方法

json对象=>json字符串

一般jquery使用ajax时,指明了dataType="json",会自动将json对象转为jsonStr提交

 $.ajax( {  
    url:‘ ‘,
    type:‘post‘,  
    dataType:‘json‘,  
    data:jsonObj,  
    success:function() { },  
    error : function() { }  
});

json字符串=>json对象

var jsonObj = $.parseJSON(jsonStr);

 二、将表单序列化为json对象

$.fn.serializeObject = function()
    {
      var o = {};
      var a = this.serializeArray();
      $.each(a, function() {
        if (o[this.name] !== undefined) {
          if (!o[this.name].push) {
            o[this.name] = [o[this.name]];
          }
          o[this.name].push(this.value || ‘‘);
        } else {
          o[this.name] = this.value || ‘‘;
        }
      });
var jsonObj= $("#formId").serializeObject();

三、java对象与json对象互相转换

 1.使用org.json实现json对象和String互转 ( 以下代码绕着弯实现了对json串的修改,对于转集合和bean对象可以灵活实现)

String jsonStr="{\"result\":[{\"id\":1,\"user\":{\"name\":\"xingwu\",\"age\":22}}],\"code\":0}";
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray jsonArray = jsonObj.getJSONArray("result");
JSONObject jsonResult = jsonArray.getJSONObject(0);
int id = jsonResult.getInt("id");
JSONObject jsonUser = jsonResult.getJSONObject("user");
String name = jsonUser.getString("name");
int age = jsonUser.getInt("age");

jsonUser.put("sex","female");
jsonResult.put("user",jsonUser);
jsonArray.put(0,jsonResult);
jsonObj.put("result",jsonArray);
System.out.println(jsonObj.toString());

2.使用json-lib包

引用:  Json-lib包是一个Java类库,提供将Java对象(包括:beans,maps,collections,java arrays 和 XML等)和JSON互相转换的功能。

   依赖包:commons-lang 2.5  commons-beanutils 1.8.0  commons-collections 3.2.1  commons-logging 1.1.1 ezmorph 1.0.6

java对象=>json对象

JSONObject jsonObject = JSONObject.fromObject(bean,jsonConfig); //javaBean   (jsonConfig可选,序列化策略)
JSONArray jsonArray = JSONArray.fromObject( array );  //数组
JSONArray jsonArray = JSONArray.fromObject( list );  //集合
JSONObject jsonObject = JSONObject.fromObject( map );  //映射
JSONArray jsonArray = JSONArray.fromObject( "[‘I‘,‘am‘,‘Chinese‘]" );  //数组型-字符串
JSONObject jsonObject = JSONObject.fromObject("{\"key\" : \"value\"}");//json串型-字符串

json对象=>java对象

myBean = (MyBean)JSONObject.toBean(jsonObj, MyBean.class);//此处也可jsonConfig
MyBean[] stus = (MyBean[]) JSONArray.toArray(jsonArray, MyBean.class);//数组
List<MyBean> list = JSONArray.toList(jsonArray, MyBean.class);//list

未完,待续。。。。

 

不同情景下的json转换

标签:

原文地址:http://www.cnblogs.com/andxingwu/p/4909774.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!