我有一个文件
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)))
通常您会在服务方法中的某个位置使用
res => res.json()
映射响应,但 json 应该具有有效的格式,否则它将无法解析。
注意,该响应是一个对象,您无法解析它,只能解析响应的正文。
return this.http.get(url,options).map((response) => this.parseResponse(response))
.catch((err) => this.handleError(err));
private handleError(error: any) {
let body = error.json();
return Observable.throw(body);
}
private parseResponse(response: Response) {
return response.json();
}