class MyClass {
constructor() {
this.foo = 3
}
}
var myClass = new MyClass()
I'd like to serialize myClass
object to json.
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
and so on.
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.
It's easy if you don't mind passing the class definition into decode.
You need to be able to reinitialize objects recursively. Having a parameterless constructor is not essential, you can get away without having one.
Here's how I perform deep copy:
The idea is simple: when serializing, a member of every known type (a type that's in
this.types
) is anointed with a member calledtypeIndex
. After deserialization, we recursively initialize every substructure that has atypeIndex
, then get rid of it to avoid polluting the structure.As with any other object you want to stringify in JS, you can use
JSON.stringify
:Also worth noting is that you can customize how
stringify
serializes your object by giving it atoJSON
method. The value used to represent your object in the resulting JSON string will be the result of calling thetoJSON
method on that object.I've came across this library which does both serialization and deserialization of complex objects (including nested objects and arrays):
https://github.com/typestack/class-transformer
It has at least two methods:
Might help to safe time for those who are looking for such solution
I know this question is old but I've been clawing my eyes out until I wrote a compact real, "safe", solution.
Deserialization returns objects that still have working methods attached to them.
The only thing you need to do is register the classes you want to use in the constructor of the serializer.
The above should be enough to get you going, but more details and minified version can be found here.
I made a module esserializer to solve this issue. It is a utility to serialize JavaScript class instance, and deserialize the "serialized-text" into an instance object, with all Class/Property/Method etc. retained.
To serialize an instance, just invoke the
serialize()
method:The internal mechanism of
serialize()
is: save the instance' property and its class name information into string, recursively.To deserialize from string, just invoke the
deserialize()
method, passing all involved classes as parameter:The internal mechanism of
deserialize()
is: manually compose the object with its prototype information, recursively.