加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:33:11 所属栏目:安全 来源:网络整理
导读:我有一个文件location.json,包含以下形式的json字符串: { "locations": [ { "id": 1,"places": [ { "id": 1,"city": "A","state": "AB" } ] }} 我创建了表单的类: export class Location{ constructor(public id: number,public places: Place[],}export c
我有一个文件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);
  }

解决方法

取决于subriber的结果,它可以是:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读