【问题标题】:angular ts: Parse a json into object of specific type角度 ts:将 json 解析为特定类型的对象
【发布时间】:2018-03-26 18:09:42
【问题描述】:

我有这样的json字符串

{"Response": 
 [
{"Amount": 0, 
 "Date": "23/1/15", 
 "Id": 12379}, 
{"Amount": 0,  
 "Id": 123}
]
}

并希望将其转换为单个类型的对象

class myobject
{
  int Amount;
  String Date;
  int Id;
  String name;
}

如果 json 字符串中没有提供值,则认为它们为 null 如果使用 JSON.parse,它会将其解析为两个不同的对象

如何在特定类型的对象中解析它?

【问题讨论】:

    标签: javascript json angular typescript


    【解决方案1】:

    您可以使用带有可选属性的接口,在属性名称后添加?

    interface MyObject
    {
       Amount?: number;
       Date?: string;
       Id?: number;
       Name?: string;
    }
    

    查看TS Playground中的示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-27
      • 2016-03-26
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 2019-07-27
      • 1970-01-01
      • 2011-08-17
      相关资源
      最近更新 更多