Issue
I'm new to Typescript and I encountered a JSON deserializing problem.
Consider this class:
class Product {
public id!: number;
public get calculatedProperty() : string {
return "Test";
};
};
As you can see calculatedProperty
is a runtime calculated property.
Also, consider that I deserialize a JSON string into my object in this way:
var jsonData = '{ "id": 2 }';
let deserialized = JSON.parse(jsonData) as Product;
The problem comes now:
- This call
console.log(deserialized.id);
returns correctly1
. - This call
console.log(deserialized.calculatedProperty);
returnsundefined
!
I really don't understand way. It seems that as Product
doesn't really create a Product
object, because If I directly invoke the constructor, new Product
, the calculated property exists.
What am I doing wrong with the JSON deserialization?
Thanks!
Solution
The JSON.parse
method isn't really for converting json into a class rather than an object.
To solve your issue you could potentially convert the json into an object like this:
let deserializedObject = JSON.parse(jsonData) as Object;
and after that you could assign the object to a class like that:
let deserialized = Object.assign(new Product(), deserializedObject);
Note that I have not tested this yet, but it should work. Also this is fine for simple objects, but not for objects with complex hierarchy.
Look into class-transformer for more information. https://github.com/typestack/class-transformer
Answered By - jstnklnr
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.