Deserialize JSON to instance of JavaScript class

Prototypical class is used to create classes in JavaScript like other programming languages.
The object return from these classes will have corresponding class information. When you to try to serialize and de-serialize this object, the class information associated with the corresponding object will be removed.

In this post, we are going to see how to retrieve this class information and make the object as the instanceof corresponding class.

The process involves two steps. They are

1. Parse using JSON.parse method.
2. Assign the constructor of the actual class to the __proto__ property of the parse JSON.

Let us see this in details.

If we have a JavaScript class like below.

 var myClass = function(){
this.a = 1;
return this.a;
};

var d = new myClass(); //result: "{a:1}";

d instanceof myClass //result: true;

In the above all works fine. The problem will arise if we try to check instanceof on the object from deserialization like shown below.

var str = JSON.stringify(d);

var d = JSON.parse(str); //result: "{a:1}
d instanceof myClass //result: false;

So now d lost its class information and hence it failed. Now we can use the below utility function to retrieve the class information.


var toCalss = function(obj, proto) {
obj.__proto__ = proto;
return obj;
}

var res = toClass(d, myClass.prototype);

res instanceof myCalss //result: true;

Now the object will have class information which makes the instanceof to work as expected.
Happy scripting..

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s