简体   繁体   English

在Angular 2打字稿中将JSON转换为通用Object []的最佳方法是什么?

[英]Whats the best way to cast JSON to generic Object[] in angular 2 typescript?

Not sure if this works as intended, but I want to convert a blob of json into an array of generic objects (the objects are malleable and can change depending on my URL). 不知道这是否按预期工作,但是我想将json的对象转换为通用对象数组(这些对象是可延展的,并且可以根据我的URL进行更改)。 Should I use JSON.parse(res.json().data) instead? 我应该改用JSON.parse(res.json()。data)吗? Thanks. 谢谢。

 return this.http.get(URL)
                       .toPromise()
                       .then(response => response.json().data as Object[]) 
                       .catch(this.handleError);
          }

The problem with your solution is that the Object type doesn't have any members (other than the usual) so any attempt to access specific properties from your JSON like id etc will create an error. 解决方案的问题是, Object类型没有任何成员(通常的成员除外),因此任何尝试从JSON(例如id等)访问特定属性的操作都会产生错误。

The correct way is as any[] : 正确的方法是as any[]

  return this.http.get(URL)
                        .toPromise()
                        .then(response => response.json().data as any[]) 
                        .catch(this.handleError);
           }

This will let you access everything that was in the JSON response (as well as everything that wasn't in the JSON response. You'll get an error at runtime). 这将使您可以访问JSON响应中的所有内容(以及JSON响应中没有的所有内容。在运行时会出现错误)。

It would be better to cast the result to a specific type, see How do I cast a JSON object to a typescript class 最好将结果强制转换为特定类型,请参见如何将JSON对象强制转换为Typescript类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM