将JavaScript对象序列化为JSON字符串 [英] serialize javascript object into a JSON string
问题描述
我有这个javascript原型:
i have this javascript prototype:
Utils.MyClass1 = function(id, member) {
this.id = id;
this.member = member;
}
并创建一个新对象:
var myobject = new MyClass1("5678999", "text");
如果我这样做:
console.log(JSON.stringify(myobject));
结果是:
{"id":"5678999", "member":"text"}
但我需要的对象类型包括在json字符串,如下:
but i need that the typeof the objects includes in json string, like this:
"MyClass1": { "id":"5678999", "member":"text"}
框架还是什么?或者我需要在类中实现toJson()方法并手动执行。
There are a fast way using any framework or something? or i need to implement the toJson() method in the class and do it manually.
谢谢!
推荐答案
确定我以这种方式解决我的问题:
ok i resolve my problem in this way:
i调整json2.js标准方法JSON.stringify()和str()函数读取一个对象时我首先放置typeof,非常简单:
i adjust the json2.js standard method JSON.stringify() and in str() function when reads an object i put first the typeof, very simple:
....
// Otherwise, iterate through all of the keys in the object.
var speechModify = false;
if(value.classname) {
partial.push('"' + value.classname + '":{');
speechModify = true;
}
.....
只有添加的是classname属性在我的课。在迭代后添加这句话:
Only to add is a classname attribute in my classes. And after the iterate adds this sentence:
if(speechModify)
partial.push("}");
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
v = v.replace("{,","{");
v = v.replace(",}", "}");
感谢所有。
这篇关于将JavaScript对象序列化为JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!