我有一个json结果,它有嵌套对象。我需要将它们转换为我的自定义对象,这些对象具有与json结果不同的属性名称。
对于父对象(Vraag
),我可以映射它们。但对于子对象(Antwoord
)我不能。
的Json
{
"question":"Vraag 1",
"answers":[
{
"answer":"Voetbal"
},
{
"answer":"Volleybal"
}
]
}
我的对象
export class Vraag {
tekst?: string;
antwoorden?: Antwoord[];
constructor(tekst?: string, antwoorden?: Antwoord[]) {
this.tekst = tekst;
this.antwoorden = antwoorden;
}
}
export class Antwoord {
tekst?: string;
constructor(tekst?: string) {
this.tekst = tekst;
}
}
服务
get(): Observable<Vraag> {
return this.http.get('the json above')
.map((response: Response) => response.json())
.map(({question , answers}) => new Vraag(question , answers)); // answers needs to be fetched inside the object too
}
那么,我怎么能像这样映射json?:
new Vraag("Vraag 1" , [new Antwoord("voetbal"),new Antwoord("volleybal")]);
答案 0 :(得分:2)
您应该将答案数组元素映射到所需对象,然后再将其传递给Vraag
构造函数。请查看以下代码段:
get(): Observable<Vraag> {
return this.http.get('the json above')
.map((response: Response) => response.json())
.map(({question , answers}) => {
answers = answers.map(answer => new Antwoord(answer));
new Vraag(question , answers));
});
}