简体   繁体   English

Typescript JSON字符串到类

[英]Typescript JSON string to class

Let be this JSON string: 让这个JSON字符串:

[
    {
        "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 ? 如何将此JSON字符串转换为MyObject列表?

If I do: 如果我做:

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

It returns a list of Object instead of a list of MyObject 它返回Object列表而不是MyObject列表

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. 如果您的数据来自服务器,您可能会将其放在any类型的变量中,您可以将其分配给该类型的数组,它将按预期工作。

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

In typescript you don't need a class implementing an interface. 在typescript中,您不需要实现接口的类。 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. 如果您的数据仍然是字符串,则可以使用JSON.parse(jsonString)将字符串解析为JavaScript对象。

See playground here 在这里看操场

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 . 你可以在这里的游乐场看看。

There is a problem when MyObject has 50 or more properties... MyObject有50个或更多属性时出现问题...

Add a constructor in your MyObject class so that it extends your json object. 在MyObject类中添加一个构造函数,以便它扩展您的json对象。

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: 在你的ajax回调中,从你的json对象创建MyObject对象:

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

I detailed the solution in that post . 我详细介绍了该帖子中的解决方案。

One more way to achieve this: 实现这一目标的另一种方法:

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

Or: 要么:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM