1

I have a class Person and after setting its properties, figuring out best way to convert that class to json object.

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

let person = new Person();
person.firstName = "FirstName";
person.lastName = "LastName";

If i do person.getJson() it should give json object as given below

{
  "firstName": "FirstName",
  "lastName": "LastName"
}

and incase lastName is not set then json object should only have firstName

{
  "firstName": "FirstName"
}

1 Answer 1

3

You don't need a getJson() method on class Person. You can just call

JSON.stringify(person);

If you really want to put in your class...

class Person {
    firstName: string;
    lastName: string;
    getJson() {
        return JSON.stringify(this);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.