【问题标题】:Typescript - auto conversion from a Json string with a date string to an object with a Date propertyTypescript - 从带有日期字符串的 Json 字符串自动转换为带有 Date 属性的对象
【发布时间】:2019-10-12 10:56:38
【问题描述】:

调用返回 JSON 的 REST 服务时,如何格式化日期以便自动将其转换为打字稿 Date 对象?

调用 REST 调用的结果是这样的消息:

{"id":3796,...,"startTempValue":"2019-05-26T19:39:01Z"}

我也试过这种 ISO 格式:

{"id":3796,...,"startTempValue":"2019-05-26T19:39:01.000Z"}

模型对象是:

export class Settings {
    public id: number;
    public shortName;
    public description: string;
    public value: string;
    public possibleValues: string;
    public startTempValue: Date;
}

startTempValue 的结果是一个字符串... ?!我希望 startTempValue 是一个 Date 对象。

当然,我可以手动将 Date 字符串转换为 Date 对象。因此,在接收 REST 服务结果时执行类似于以下代码的操作。 但应该有更好的方法。 另一种选择是在服务器上将其转换为纪元(毫秒)。这是可能的,但这个“字符串”变体仍然更具可读性。

if ( this.settings[i].startTempValue !== undefined && 
     this.settings[i].startTempValue !== null) {
    this.settings[i].startTempValue = new Date(this.settings[i].startTempValue);
} else {
    this.settings[i].startTempValue = null;
}

【问题讨论】:

    标签: json typescript rest


    【解决方案1】:

    JSON 只处理数字、字符串、数组和对象等原语。

    JSON 中没有描述其内容含义的信息。所以即使某些东西在你看来像是一个日期,它仍然只是一个字符串。

    那么你怎么能手动转换呢?好吧,如果您提前知道哪些属性名称是 always 日期,您可以循环遍历结果并抢先转换这些。或者您可以遍历所有值并获取任何看起来像日期的东西并自动转换。

    第三种选择是使用某种模式将某些事物标记为日期并将其用于自动转换。

    关键是没有内置的方法来推断这一点,这取决于你用你的数据做其他事情

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-22
      • 2017-11-11
      • 2021-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多