【问题标题】:Typescript, Angular 2 - Parse Json to object in httpTypescript,Angular 2 - 将 Json 解析为 http 中的对象
【发布时间】:2017-10-15 20:49:47
【问题描述】:

我有一个文件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)
  • 这没有映射我的 json。

标签: json angular parsing typescript angular2-services


【解决方案1】:

取决于订阅者的结果是什么:

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

【讨论】:

  • 我得到了这个错误:EXCEPTION: Unexpected token o in JSON at position 1 当我做JSON.parse
  • 再一次,这取决于你得到什么。添加这个:console.log(res, typeof res) 看看实际的反应是什么
【解决方案2】:

通常你会在服务方法的某个地方使用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();
  }

【讨论】:

  • 你能举个例子吗?
  • 谢谢,但我仍然看到了映射...我应该可以在 NgFor 中 locations
  • 如果它发出任何东西,但 json 具有不同的结构,所以你最好转换结果
  • .subscribe(res => this.locations = res.json().locations);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-04
  • 2017-03-18
  • 2021-05-15
  • 2016-07-27
  • 2017-10-25
  • 1970-01-01
  • 2020-05-02
相关资源
最近更新 更多