Skip to content Skip to sidebar Skip to footer

Serializing An Es6 Class Object As Json

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

Solution 1:

As with any other object you want to stringify in JS, you can use JSON.stringify:

JSON.stringify(yourObject);

classMyClass {
  constructor() {
    this.foo = 3
  }
}

var myClass = newMyClass()

console.log(JSON.stringify(myClass));

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.

Solution 2:

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.


classSerializer{
    constructor(types){this.types = types;}
    serialize(object) {
        let idx = this.types.findIndex((e)=> {return e.name == object.constructor.name});
        if (idx == -1) throw"type  '" + object.constructor.name + "' not initialized";
        returnJSON.stringify([idx, Object.entries(object)]);
    }
    deserialize(jstring) {
        let array = JSON.parse(jstring);
        let object = newthis.types[array[0]]();
        array[1].map(e=>{object[e[0]] = e[1];});
        return object;
    }
}

classMyClass {
    constructor(foo) {this.foo = foo;}
    getFoo(){returnthis.foo;}
}

var serializer = newSerializer([MyClass]);

console.log(serializer.serialize(newMyClass(42)));
//[0,[["foo",42]]]console.log(serializer.deserialize('[0,[["foo",42]]]').getFoo());
//42

The above should be enough to get you going, but more details and minified version can be found here.

Solution 3:

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:

plainToClass() -> json obj to class
classToPlain() -> class to json obj

Solution 4:

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:

constESSerializer = require('esserializer');
let serializedString = ESSerializer.serialize(anObject);

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:

constESSerializer = require('esserializer');
constClassA = require('./ClassA');
constClassB = require('./ClassB');
constClassC = require('./ClassC');

let deserializedObj = ESSerializer.deserialize(serializedString, [ClassA, ClassB, ClassC]);

The internal mechanism of deserialize() is: manually compose the object with its prototype information, recursively.

Solution 5:

It's easy if you don't mind passing the class definition into decode.

// the codeconstencode = (object) => JSON.stringify(Object.entries(object))

constdecode = (string, T) => {
  const object = newT()
  JSON.parse(string).map(([key, value]) => (object[key] = value))
  return object
}

// test the codeclassA {
  constructor(n) {
    this.n = n
  }

  inc(n) {
    this.n += n
  }
}

const a = newA(1)
const encoded = encode(a)
const decoded = decode(encoded, A)
decoded.inc(2)
console.log(decoded)

Post a Comment for "Serializing An Es6 Class Object As Json"