你的位置:首页 > Java教程

[Java教程]Object转换为JSON格式字符串


简介:

把JS的Object转换为Json字符串。

代码:

function (object) {  // Object转换为josn  var json = "";  switch (jQuery.type(object)) {    case "array":      json = "[";      $.each(object, function (i, item) {        json += $.sinopec.ObjectToJson(item) + ",";      });      if (json != "[" && json.length > 0) json = json.substr(0, json.length - 1);      json += "]";      break;    case "object":      json = "{";      $.each(object, function (key, value) {        if (jQuery.type(value) == "object") {          json += "\"" + key + "\":" + $.sinopec.ObjectToJson(value) + ",";        } else if (jQuery.type(value) == "array") {          json += "\"" + key + "\":" + $.sinopec.ObjectToJson(value) + ",";        } else {          json += "\"" + key + "\":\"" + value + "\",";        }      });      if (json != "{" && json.length > 0) json = json.substr(0, json.length - 1);      json += "}";      break;    default:      json = "\"" + object + "\"";      break;  }  return json;}

示例:

var data = {};data['Username'] = $('#username').val();data['Password'] = $('#password').val();var params = {};params['url'] = '/Demo/SignIn';params['data'] = data;

结果:

{  "url": "/Demo/SignIn",  "data": {    "Username": "demo",    "Password": "test"  }}