【发布时间】:2019-02-04 12:58:42
【问题描述】:
我有以下 JSON 数组,其中 id 键是一个字符串(呵呵)。
"locations": [
{
"default_currency_id": "17",
"continent": "1",
"country_code": "AL",
"gift_value": "150",
"alert": "TEST",
"caption": "Albania",
"id": "1"
},
我想使用基于模型中定义的值的自动转换,而不是使用 Number 函数(请参阅附件 sn-p):请问如何以正确的方式实现?理想情况下,我想将 json Array 放入类型化模型中,无需手动解析(如您在 for 循环中所见)
export class Location {
default_currency_id: number;
continent: string;
country_code: string;
gift_value: string;
alert: string;
caption: string;
id: number;
}
parseDataset(data: any) {
console.log('parseDataset');
console.log(data);
if(data.locations_gifts != null) {
//this.dataSet.locations = data.locations_gifts;
for(let o of data.locations_gifts){//HOW TO AVOID MANUAL PARSING?
console.log(o);
let item: Location = <Location>{
default_currency_id: Number(o.default_currency_id), //HOW TO AVOID MANUAL CONVERSION?
};
this.dataSet.locations.push(item);
}
}
console.log(this.dataSet)
}
【问题讨论】:
-
即使您的 JSON 是字符串化的,您也需要手动转换 ID,因为它是以字符串形式出现的。即,如果 id 是 "default_currency_id": 17,这样,您就不必转换,但由于 id 带有字符串,您需要转换
-
是的,但我要求通过某种方式自动应用模型中定义的策略?(我无权修改源 Json)
标签: typescript casting type-conversion