我有一个文件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字符串解析为object?我做了这样的事情:
...
export class DashboardComponent {
locations: Locations[];
constructor(private locationService:LocationService) {
this.getLocations()
}
getLocations(){
this.locationService.get('assets/location.json')
.subscribe(res => this.location = res);
}
答案 0 :(得分:6)
取决于潜艇的结果,可以是:
.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)))
答案 1 :(得分:0)
通常你在服务方法的某处用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();
}