我正在使用Angular2.4并希望使用TypedJSON库(typedjson-npm)解析JSON。但我无法理解如何在以下特定情况下这样做。
我有JSON数据的类,例如:
@JsonObject
export class UserModel {
@JsomMember
public 'name': string;
@JsonMember
public 'email': string;
// I'm changing the name to have the one case-style for all properties, it's okay
@JsonMember({ name: 'registration_date' })
public 'registrationDate': string;
}
然后我从服务器获得JSON,如:
[
{
"name": "John",
"email": "john@mail.com",
"registration_date": "1497365370047"
},
{
"name": "Mike",
"email": "mike@mail.com",
"registration_date": "1497365370047"
}
]
现在我要解析这个JSON。我正在尝试像
这样的东西this.http
.get('http://zzzz.com/api/users-list')
.subscribe((response: Response) => {
let data: UserModel[] = TypedJSON.parse(response.json(), UserModel[]);
});
但我看到PHPStorm中的错误(最后两个符号下的红色下划线 - )))
预期的表达
我在文档中没有看到如何解决此问题的任何示例。 所以,我的问题是:如何用这个库解析自定义类型对象的数组?
或者,有人可以向我推荐一些npm库在Angular2中使用它,它可以简单地替换上面提到的属性名称吗?
答案 0 :(得分:2)
为此,我们需要遍历每个json数据,
试试这个:
this.http
.get('http://zzzz.com/api/users-list')
.subscribe((response: Response) => {
let resJson = response.json();
let data: UserModel[] = resJson.map(res => TypedJSON.parse(res, UserModel); );
});