I
I
Ilya2015-09-11 14:29:28
Angular
Ilya, 2015-09-11 14:29:28

How to convert json to model/class?

I have a model for angular 2

class Post {
  ID: number;
  Name: string;
  Text: string;
  UserID: number;
}

And there is a response in JSON
[
  {
    "ID": 1,
    "Name": "123asdasd",
    "Text": "321as5f1asdkjashkdjashdkj",
    "UserID": 0
  },
  {
    "ID": 2,
    "Name": "123asdasd",
    "Text": "321as5f1asdkjashkdjashdkj",
    "UserID": 0
  }
]

How should I convert this JSON to an array?
I am now converting by enumeration, I do not think that this is correct.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2015-09-11
@FireGM

JSON.parse
In general, ask there on the server what would return the correct Content-type to you, and then the angular will do it itself. Or read about interceptors
If the task is to "map data onto an object". then...
return data.map((item) => Post.fromObject(item));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question