gpt4 book ai didi

json - Typescript,Angular 2 - 将 Json 解析为 http 中的对象

转载 作者:太空狗 更新时间:2023-10-29 17:48:20 24 4
gpt4 key购买 nike

我有一个文件 location.json,包含以下形式的 JSON 字符串:

{
"locations": [
{
"id": 1,
"places": [
{
"id": 1,
"city": "A",
"state": "AB"
}
]
}
}

我创建了以下形式的类:

export class Location{
constructor(public id: number,
public places: Place[],
}

export class Place {
constructor(
public id: number,
public city: string,
public state: string
}

如何将 JSON 字符串解析为对象?我做了这样的事情:

...
export class DashboardComponent {

locations: Locations[];

constructor(private locationService:LocationService) {
this.getLocations()
}

getLocations(){
this.locationService.get('assets/location.json')
.subscribe(res => this.location = res);
}

最佳答案

根据订阅者的结果,它可以是:

.map(res => this.location = res.json().locations);

或者:

.subscribe(res => this.location = JSON.parse(res).locations);

但请记住,这不会为您的类实例化实例,它只会将值分配为匹配以下内容的常规 js 对象:

interface Location {
id: number;
places: Place[];
}

interface Place {
id: number;
city: string;
state: string;
}

如果你想要类的实例,你需要做类似的事情:

JSON.parse(res)
.locations.map(location => new Location(location.id,
location.places.map(place => new Place(place.id, place.city, place.state)))

关于json - Typescript,Angular 2 - 将 Json 解析为 http 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44007094/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com