作者:---残月_235_999 | 来源:互联网 | 2022-08-19 14:46
正如标题所言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; istrArr.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 "";
}