Typescript JSON字符串进行分类 [英] Typescript JSON string to class

查看:145
本文介绍了Typescript JSON字符串进行分类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让这个JSON字符串为

Let be this JSON string:

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

让我们成为此类:

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

如何将该JSON字符串强制转换为MyObject的列表?

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

如果我这样做:

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

它返回Object的列表而不是MyObject

推荐答案

您在这里不一定需要一个类.您可以只使用界面

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

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

然后您可以编写:

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.

如果您的数据仍为字符串形式,则可以使用JSON.parse(jsonString)将该字符串解析为JavaScript对象.

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

查看游乐场此处

这篇关于Typescript JSON字符串进行分类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆