I am trying to cast a JSON object like the following example:
class Person {
constructor(
public firstName,
public lastName
) {}
function getName() {
return this.firstName + “ “ + this.lastName;
}
}
The goal is to parse the JSON which looks like this:
{
firstName: “Max“,
lastName: “Mustermann“
}
to an instance of the above class to access all properties and methods.
Is there an easy way to create a function which can make such a functionality possible for such type of JSONs/classes?
Also nested objects should be possible.
I can write a factory method for every different class but there should be an better way to get such functionality.
2
Answers
Use Object.assign
Create your class like this, observe the constructor
Pass the json into this constructor
To parse the given JSON to an instance of the Person class in TypeScript, you can follow these steps:
In the code above, the JSON data is stored in the json variable. We use JSON.parse() to convert the JSON string into an object. Then, we create a new instance of the Person class by passing the firstName and lastName properties from the parsed JSON object.
Now, you can access the properties and methods of the person instance, such as person.getName(), to get the full name.