将JavaScript对象序列化为JSON字符串 [英] Serialize JavaScript object into JSON string

查看:92
本文介绍了将JavaScript对象序列化为JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个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 for the type of the objects to be included in the JSON string, like this:

"MyClass1": { "id":"5678999", "member":"text"} 

是否有使用框架或其他东西快速做到这一点?或者我是否需要在类中实现 toJson()方法并手动执行?

Is there a fast way to do this using a framework or something? Or do I need to implement a toJson() method in the class and do it manually?

推荐答案

var myobject = new MyClass1("5678999", "text");
var dto = { MyClass1: myobject };
console.log(JSON.stringify(dto));

编辑:

JSON.stringify 将对您班级的所有'属性进行字符串化。如果你想只保留其中一些,你可以像这样单独指定它们:

JSON.stringify will stringify all 'properties' of your class. If you want to persist only some of them, you can specify them individually like this:

var dto = { MyClass1: {
    property1: myobject.property1,
    property2: myobject.property2
}};

这篇关于将JavaScript对象序列化为JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆