0

Let say I have a Object:

class Person{
id: number;
name: string;
}

And Json from API:

{
"id": "10",
"name": "Person Name",
"email": "[email protected]"
}

How to convert from JSON to Person object, excatly variables that is in Person class?

I tried this:

Object.assign(Person.prototype, this.jsonList))

but i'ts not working

2
  • Add a constructor, and call it: new Person(json.id, json.name)? Commented May 27, 2017 at 14:34
  • Method Object.assign assigns all properties, but email doesnt exists in Person Commented May 27, 2017 at 14:35

1 Answer 1

1

The information about what properties are declared in a class is "metadata", and is not directly accessible. Hence, there is no straightforward way to copy only those properties present in a class from some input which might contain additional unwanted properties, other than explicitly enumerating them.

The feature of JavaScript/TypeScript which does have access to such metadata is decorators. Therefore, to solve your problem in a generalized way requires such a decorator. The decorator could generate a static method which copied just those properties which actually exist on the class. That would look like that:

@ConstructFromJsonWithExtraGarbage()
class Person {
}

const sally = Person.constructWithExtraGarbage(
  {id: 1, name: "Sally", email: "[email protected]"});

Actually writing this decorator is beyond the scope of this answer.

Sign up to request clarification or add additional context in comments.

7 Comments

I don't need email. Object.assign method copies all properties
there can be a lot of unnecessary properties in Json. I need exactly which are described in Person. I need mapping approach. But Object.assign extends Person with all properties
So replace Object.assign() by this.id = person.id; this.name = person.name;. What's the concrete problem?
This is the problem, I must write all properties by hand, I cant find auto mapper.
What you want is a "class decorator". You can find more information at typescriptlang.org/docs/handbook/decorators.html.
|

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.