0

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.

Zharin
  • 75
  • 12
  • "*I can write a factory method for every different class but there should be an better way to get such functionality.*" - actually no, writing a factory method per class is the only proper solution. This is necessary to deal with different constructor arguments and internal state - even if the class does not yet have these, it might get them later, you should always simply call the factory method. – Bergi May 29 '23 at 12:21

1 Answers1

1

Use Object.assign

Create your class like this, observe the constructor

class Person {
       public firstName: string; 
       public lastName: string;

       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);
Amit Kumar Singh
  • 4,393
  • 2
  • 9
  • 22