JavaScript || Convert & Deserialize JSON & Simple Object To A Class Type Using Vanilla JavaScript

Print Friendly, PDF & Email

The following is a module which demonstrates how to convert a simple object to a class type, as well as parsing a JSON serialized object back to its class type.


1. Convert Simple Object To Typed Class

The example below demonstrates how to convert a simple object to its class type. Converting the simple object to its class type allows us to use its class functions.

The ‘Utils.ctype‘ function converts the object to a class, which allows to use the functions from that class.


2. Deserialize Simple JSON Object To Typed Class

Parsing a simple JSON string and converting it to a typed class can be achieved in a similar way. The example below demonstrates this.


3. Deserialize Simple Nested JSON Object To Typed Class

Parsing a multi-leveled, nested JSON string and converting it to a typed class is done a little differently. We have to map the JSON structure with the values we want to convert. This is done using ‘Utils.ctypeMap‘.

The example below demonstrates this.


4. Deserialize Complex Nested JSON Object To Typed Class

Parsing a complex JSON string and converting it to a typed class can be achieved in a similar way. The example below demonstrates this.


5. Utils.ctype/ctypeMap Namespace

The following is the Utils.js Namespace. Include this in your project to start using!

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Was this article helpful?
👍 YesNo

Leave a Reply