function toJSON(obj){
var objInn = obj;
if (objInn == null) {
return null;
}
switch (objInn.constructor) {
case String:
//s = "'" + str.replace(/(["\\])/g, "\\$1") + "'"; string含有单引号出错
objInn = '"' + objInn.replace(/(["\\])/g, '\\$1') + '"';
objInn= objInn.replace(/\n/g,"\\n");
objInn= objInn.replace(/\r/g,"\\r");
objInn= objInn.replace("<", "<");
objInn= objInn.replace(">", ">");
objInn= objInn.replace(/%/g, "%25");
objInn= objInn.replace(/&/g, "%26");
return objInn;
case Array:
var arr = [];
for(var i=0,len=objInn.length;i<len;i++) {
arr.push(SuperMap.Util.toJSON(objInn[i]));
}
return "[" + arr.join(",") + "]";
case Number:
return isFinite(objInn) ? String(objInn) : null;
case Boolean:
return String(objInn);
case Date:
var dateStr = "{" + "'__type':\"System.DateTime\"," +
"'Year':" + objInn.getFullYear() + "," +
"'Month':" + (objInn.getMonth() + 1) + "," +
"'Day':" + objInn.getDate() + "," +
"'Hour':" + objInn.getHours() + "," +
"'Minute':" + objInn.getMinutes() + "," +
"'Second':" + objInn.getSeconds() + "," +
"'Millisecond':" + objInn.getMilliseconds() + "," +
"'TimezoneOffset':" + objInn.getTimezoneOffset() + "}";
return dateStr;
default:
if (objInn["toJSON"] != null && typeof objInn["toJSON"] === "function") {
return objInn.toJSON();
}
if (typeof objInn === "object") {
if (objInn.length) {
var arr = [];
for(var i=0,len=objInn.length;i<len;i++)
arr.push(toJSON(objInn[i]));
return "[" + arr.join(",") + "]";
}
var arr=[];
for (attr in objInn) {
//为解决SuperMap.Geometry类型头json时堆栈溢出的问题,attr == "parent"时不进行json转换
if (typeof objInn[attr] !== "function" && attr !== "CLASS_NAME" && attr !== "parent") {
arr.push("'" + attr + "':" + toJSON(objInn[attr]));
}
}
if (arr.length > 0) {
return "{" + arr.join(",") + "}";
} else {
return "{}";
}
}
return objInn.toString();
}
};
Json转换
最新推荐文章于 2024-04-12 15:16:48 发布