我已经生成了 string :
string str = [{"id":1,"name":"Angular"},{"id":2,"name":"SpringBoot"}]
我想将其转换为对象数组,以实现以下目的:
listexps: Expertise[];
listexps = [{"id":1,"name":"Angular"},{"id":2,"name":"SpringBoot"}];
专业类是
export class Expertise
{
id: number;
name: string;
}
我尝试过:
let array = str .replace('[{','').replace('}]','').split("},{").map(String);
但是那并不能解决我的问题,我得到了:
"id":1,"name":"Angular","id":2,"name":"SpringBoot"
代替
[{"id":1,"name":"Angular"},{"id":2,"name":"SpringBoot"}];
您是否对解决该问题有任何想法? 非常感谢。
答案 0 :(得分:1)
您需要的是JSON.parse;它将字符串转换为对象;
相关的 ts :
import { Component } from '@angular/core';
export class Expertise {
id: number;
name: string;
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular';
strIntoObj: Expertise[];
constructor() {
let str: string = '[{"id":1,"name":"Angular"},{"id":2,"name":"SpringBoot"}]';
this.strIntoObj = JSON.parse(str);
console.log(this.strIntoObj);
}
}