Ben
Ben

Reputation: 4110

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

Upvotes: 3

Views: 17072

Answers (4)

OlegI
OlegI

Reputation: 6010

One more way to achieve this:

var data: any = getFromServer();
var myObjectArray = data as MyObject;

Or:

var data: any = getFromServer();
var myObjectArray = <MyObject>dataMyObject;

Upvotes: 0

Anthony Breneli&#232;re
Anthony Breneli&#232;re

Reputation: 63500

There is a problem when MyObject has 50 or more properties...

Add a constructor in your MyObject class so that it extends your json object.

export class MyObject {
    constructor( json: any )
    {
      $.extend(this, json);
    }
    id : number;
    text : string;

    methodOnMyObject() {...}
}

In your ajax callback, create the MyObject object from your json Object:

let newObject = new MyObject( json );
newObject.methodOnMyObject();

I detailed the solution in that post.

Upvotes: 1

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249656

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

Upvotes: 9

toskv
toskv

Reputation: 31600

You will need to create a constructor for your class, and call it for each item in the list you receive.

export class MyObject{
    constructor(public id: number, public text: string) { }
}

let data = [
  {
    "id": 1,
    "text": "Jon Doe"
  },
  {
    "id": 1,
    "text": "Pablo Escobar"
  }
];

let objects = data.map(o => new MyObject(o.id, o.text));

You can check it out in the playground here.

Upvotes: 6

Related Questions