【问题标题】:Typescript automatic type conversion during the JSON parsing?JSON解析期间的Typescript自动类型转换?
【发布时间】: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


【解决方案1】:

你不能那样做。 TypeScript 可帮助您在开发中验证代码,而不是在运行时验证。所以动态响应数据的数据转换不在它的范围内(至少到现在为止)

【讨论】:

    【解决方案2】:

    我认为您可以使用 JSON.parse() 中的 reviver 选项 我用它将我的 JSON 日期(它是字符串)转换为 Javascript 日期对象 这里的例子: https://mariusschulz.com/blog/deserializing-json-strings-as-javascript-date-objects

    【讨论】:

      【解决方案3】:

      您可以像这样在代码中使用签名来做到这一点:

      const sign = {
        default_currency_id: "integer",
        continent: "string",
        country_code: "string",
        gift_value: "string",
        alert: "string",
        caption: "string",
        id: "integer"
      }
      
      parseDataset(data: any) {
        console.log(data);
        let dataDecoded:any = {};
        Object.keys(this.sign).forEach((key, index) => {
      
          let value = data[index];
      
          if (value) {
            switch (this.sign[key]) {
              case 'integer': 
                value = parseInt(value);
                break;
      
              default: value = value.toString();
            }
      
            dataDecoded[key] = value;
          }
        });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-14
        相关资源
        最近更新 更多