skip to Main Content

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


  1. Use Object.assign

    Create your class like this, observe the constructor

    class Person {
    
           public constructor(init?: Partial<Person>) {
            Object.assign(this, init);
           }
    
          function getName() {
            return this.firstName + “ “ + this.lastName;
          }
       }
      
    

    Pass the json into this constructor

    let person =  new Person({firstName: "A", lastName: "B" });
    console.log(person);
    
    Login or Signup to reply.
  2. To parse the given JSON to an instance of the Person class in TypeScript, you can follow these steps:

    1. Define the Person class with the constructor and getName method:
    class Person {
      constructor(public firstName: string, public lastName: string) {}
    
      getName(): string {
        return this.firstName + " " + this.lastName;
      }
    }
    
    1. Parse the JSON and create an instance of the Person class:
    const json = `{
       firstName: "Max",
       lastName: "Mustermann"
    }`;
    
    const data = JSON.parse(json);
    const person = new Person(data.firstName, data.lastName);
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search