Ben Ben - 1 month ago 6
JSON Question

Typescript JSON string to class

Let be this JSON string:

` [
{
"id": 1,
"text": "Jon Doe"
},
{
"id": 1,
"text": "Pablo Escobar"
}
]`


Let be this class:

export class MyObject{
id: number;
text: string;
}


How can I cast this JSON string to list of MyObject?

If I do:

console.log(<MyObject[]>JSON.parse(json_string));


It returns a list of
Object
instead of a list of
MyObject

Answer

You don't necessarily need a class here. You can just use an interface

export interface MyObject{
  id: number;
  text: string;
}

Then you can just write:

var myObjArray : MyObject[] =  [
  {
    "id": 1,
    "text": "Jon Doe"
  },
  {
    "id": 1,
    "text": "Pablo Escobar"
  }
];

If you data comes from the server, you will probably have it in a variable of type any, and you can just assign it to an array of that type and it will work as expected.

var data: any = getFromServer();
var myObjectArray:MyObject[] = data;

In typescript you don't need a class implementing an interface. Any object literal that satisfies the interface contract will do.

If your data is still in string for you can just use JSON.parse(jsonString) to parse the string to JavaScript objects.

See playground here

Comments