I read a JSON object from a remote REST server. This JSON object has all the properties of a typescript class (by design). How do I cast that received JSON object to a type var?
I don't want to populate a typescript var (ie have a constructor that takes this JSON object). It's large and copying everything across sub-object by sub-object & property by property would take a lot of time.
Update: You can however cast it to a typescript interface!
In my case it works. I used functions Object.assign (target, sources ...). First, the creation of the correct object, then copies the data from json object to the target.Example :
And a more advanced example of use. An example using the array.
I've created a simple tool to do this https://beshanoe.github.io/json2ts/ Unlike json2ts.com it works directly in browser and doesn't send your data to unknown servers. Also it has multiple settings. I'll work to improve it's functionality
An old question with mostly correct, but not very efficient answers. This what I propose:
Create a base class that contains init() method and static cast methods (for a single object and an array). The static methods could be anywhere; the version with the base class and init() allows easy extensions afterwards.
Similar mechanics (with assign()) have been mentioned in @Adam111p post. Just another (more complete) way to do it. @Timothy Perez is critical of assign(), but imho it is fully appropriate here.
Implement a derived (the real) class:
Now we can cast an object retrieved from service:
All hierarchy of SubjectArea objects will have correct class.
A use case/example; create an Angular service (abstract base class again):
The usage becomes very simple; create an Area service:
get() method of the service will return a Promise of an array already cast as SubjectArea objects (whole hierarchy)
Now say, we have another class:
Creating a service that retrieves data and casts to the correct class is as simple as:
I see no mention of json-typescript-mapper: https://www.npmjs.com/package/json-typescript-mapper. It looks like a combination of @PhilipMiglinci's find, and @Pak's answer, as far as I can tell.
I used this library here: https://github.com/pleerock/class-transformer
Implementation:
Sometimes you will have to parse the JSON values for plainToClass to understand that it is a JSON formatted data
I had the same issue and I have found a library that does the job : https://github.com/pleerock/class-transformer.
It works like this :
It supports nested childs but you have to decorate your class's member.