简体   繁体   中英

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"}, {...}, {...}] .

Is this possible? Because from the Angular 2 tutorial you can do the opposite with the line:

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

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

use JSON.stringify() most thing in js are object.

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

so the Heros is the Array you want :)

You can add a toJSON() function in your class. This function gets called automatically when JSON.stringify() is called on your class instance

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

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

Output

{
  firstName: "Tom"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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