将ES6类对象序列化为JSON [英] Serializing an ES6 class object as JSON
问题描述
class MyClass {
constructor() {
this.foo = 3
}
}
var myClass = new MyClass()
我想序列化 myClass
对象为json。
I'd like to serialize myClass
object to json.
我能想到的一个简单方法是,因为每个成员实际上都是javascript对象(数组等)。我想我可以维护一个变量来保存成员变量。
One easy way I can think of is, since every member is actually javascript object (array, etc..) I guess I can maintain a variable to hold the member variables.
this.prop.foo = this.foo
等等。
我希望为类对象找到 toJSON / fromJSON
库,因为我将它们与其他语言如swift一起使用/ java,但找不到一个javascript。
I expected to find a toJSON/fromJSON
library for class objects since I used them with other languages such as swift/java, but couldn't find one for javascript.
也许类构造太新了,或者我问的问题可以在没有库的情况下以某种方式轻松实现。
Maybe class construct is too new, or what I'm asking can be somehow easily achieved without a library.
推荐答案
与想要在JS中进行字符串化的任何其他对象一样,您可以使用 JSON.stringify
:
As with any other object you want to stringify in JS, you can use JSON.stringify
:
JSON.stringify(yourObject);
class MyClass {
constructor() {
this.foo = 3
}
}
var myClass = new MyClass()
console.log(JSON.stringify(myClass));
另外值得注意的是,您可以自定义 stringify $ c的方式$ c>通过给它一个
toJSON
方法。用于在结果JSON字符串中表示对象的值将是在该对象上调用 toJSON
方法的结果。
Also worth noting is that you can customize how stringify
serializes your object by giving it a toJSON
method. The value used to represent your object in the resulting JSON string will be the result of calling the toJSON
method on that object.
这篇关于将ES6类对象序列化为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!