json转String与String转json及判断对象类型示例代码
function ajaxGetMenuList(){
$.getJSON("login.do", function(json){
var r = "";
zNodes += "[";
$(json.menuList).each(function(i){
r = json.menuList[i];
if(i>0) zNodes += ",";
zNodes += '{';
zNodes += 'id:'+r.SId;
zNodes += ', pId:'+r.SPid;
zNodes += ', name:"'+r.STitle;
if(r.SPid == 0) zNodes += '", open:true';
else zNodes += '"';
zNodes += '}';
})
zNodes += "]";
zNodes = stringToJSON(zNodes);
createTree(zNodes);
});
}
/**
* json转String
* @param {Object} obj
* @memberOf {TypeName}
* @return {TypeName}
*/
function jsonToString (obj){
var THIS = this;
switch(typeof(obj)){
case 'string':
return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';
case 'array':
return '[' + obj.map(THIS.jsonToString).join(',') + ']';
case 'object':
if(obj instanceof Array){
var strArr = [];
var len = obj.length;
for(var i=0; i<len; i++){
strArr.push(THIS.jsonToString(obj[i]));
}
return '[' + strArr.join(',') + ']';
}else if(obj==null){
return 'null';
}else{
var string = [];
for (var property in obj) string.push(THIS.jsonToString(property) + ':' + THIS.jsonToString(obj[property]));
return '{' + string.join(',') + '}';
}
case 'number':
return obj;
case false:
return obj;
}
}
/**
* String转json
* @param {Object} obj
* @return {TypeName}
*/
function stringToJSON(obj){
return eval('(' + obj + ')');
}
//判断对象类型
function getType(x){
if(x==null){
return "null";
}
var t= typeof x;
if(t!="object"){
return t;
}
var c=Object.prototype.toString.apply(x);
c=c.substring(8,c.length-1);
if(c!="Object"){
return c;
}
if(x.constructor==Object){
return c
}
if("classname" in x.prototype.constructor
&& typeof x.prototype.constructor.classname=="string"){
return x.constructor.prototype.classname;
}
return "<unknown type>";
}