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

5
我有一个名为 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);
  }

也许尝试使用 JSON.Parse(res)。 - federico scamuzzi
这没有映射我的JSON。 - kenadet
2个回答

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)))

当我使用JSON.parse时,出现了这个错误:EXCEPTION: Unexpected token o in JSON at position 1 - kenadet
再次强调,这取决于你得到了什么。添加这个:console.log(res, typeof res) 来查看实际响应是什么。 - Nitzan Tomer

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();
  }

你能举个例子吗? - kenadet
谢谢,但我已经看到了映射...我应该能够在NgFor中使用locations - kenadet
如果输出不是JSON或结构不同,最好将结果进行转换。 - Roman C
.subscribe(res => this.locations = res.json().locations); - Roman C

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接