【发布时间】:2017-10-17 08:26:47
【问题描述】:
我想把一个 json 字符串数组变成一个对象数组。 在这种情况下,我有一个从后端接收的字符串
[{"id_pk":3,"heroname":"myherooo"},{"id_pk":12,"heroname":"Narco"}]
我想把这个字符串变成一个英雄数组,然后返回它。
我当前的代码:
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => {
console.log(response);
let heroes: Hero[];
let jo = response.text(); // [{"id_pk":3,"heroname":"myherooo"},{"id_pk":12,"heroname":"Narco"}]
console.log("jo: "+jo);
for(let i=0;i<jo.length;i++){
console.log("ele: "+JSON.parse(response.text()[i])); // SyntaxError: Unexpected end of JSON input
heroes[i] = JSON.parse(response.text()[i]);
}
heroes;
})
.catch(this.handleError);
}
有人可以帮忙吗?
更新:
这是解决方案:
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.map (t=>t.json())
.toPromise()
.then(response => response.map(i => new Hero(i.id_pk, i.heroname)))
.catch(this.handleError);
}
【问题讨论】: