简体   繁体   English

TypeScript 类到 JSON

[英]TypeScript class to JSON

I have a class array where the class looks like:我有一个类数组,其中的类如下所示:

class Tag{
    select: string;
    search: string;
}

I want to convert it to JSON where it'll probably look like [{select: "blah", search: "bleh"}, {...}, {...}] .我想将它转换为 JSON,它可能看起来像[{select: "blah", search: "bleh"}, {...}, {...}]

Is this possible?这可能吗? Because from the Angular 2 tutorial you can do the opposite with the line:因为从 Angular 2 教程中,您可以使用以下行进行相反的操作:

.map((r: Response) => r.json().data as Hero[]);

您可以使用JSON.stringify()将 javascript 对象转换为 json 字符串 由于类和类的实例是 javascript 中的对象,因此您也可以将它们字符串化

use JSON.stringify() most thing in js are object.使用JSON.stringify()js中大多数东西都是对象。

class Hero{}
let Heros:Hero[] = JSON.stringify(response.data);

so the Heros is the Array you want :)所以Heros是你想要的数组 :)

You can add a toJSON() function in your class.您可以在类中添加toJSON()函数。 This function gets called automatically when JSON.stringify() is called on your class instance当在您的类实例上调用JSON.stringify()时,将自动调用此函数

class Person{
  constructor(readonly name){}

  toJSON(){
    return {
      firstName: this.name
    }
  }
}

Now if you console.log you class instance using JSON.stringify you will see this result现在,如果您使用JSON.stringify使用console.log类实例,您将看到此结果

const person = new Person("Tom"); const person = new Person("Tom"); console.log(JSON.stringify(person)); console.log(JSON.stringify(person));

Output输出

{
  firstName: "Tom"
}

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

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