Over the years I have used a very simple pattern for serializing and deserializing model objects using JSON.
Summary
Provide an instance toJSON function and a static fromJSON function. The static function will leverage the fact that its context is the constructor function. It calls this to create a new instance with the deserialized config data.
Uses
- Store the model in Local Storage.
- Send the model as a parameter in a HTTP request.
- Override the object’s
toStringto return JSON instead of[object Object].
Example
Below is a bare-bones example to illustrate the usage of this pattern.