如何从打字稿中的 json 响应中获取日期对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35917808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get Date object from json Response in typescript
提问by Vladimir Nani
Here is my json:
这是我的json:
{
"data": [
{
"comment": "3541",
"datetime": "2016-01-01"
}
]
}
Here is model:
这是模型:
export class Job {
constructor(comment:string, datetime:Date) {
this.comment = comment;
this.datetime = datetime;
}
comment:string;
datetime:Date;
}
Query:
询问:
getJobs() {
return this._http.get(jobsUrl)
.map((response:Response) => <Job[]>response.json().data)
}
Problem is that after casting to Job[]i expect datetimeproperty to be Datebut it is string. Shouldn't it cast to Date object? What am i missing here?
问题是,在强制转换后,Job[]我希望datetime属性Date是字符串,但它是字符串。它不应该转换为 Date 对象吗?我在这里缺少什么?
采纳答案by Amid
@Gunter is absolutely correct. The only thing I would like to add is actually how to deserialize json object keeping its date properties as dates and not strings (from the referenced post its not that easy to see this approach).
@Gunter 是绝对正确的。我想添加的唯一一件事实际上是如何反序列化 json 对象,使其日期属性保持为日期而不是字符串(从引用的帖子中看到这种方法并不容易)。
Here is my attempt:
这是我的尝试:
export class Helper
{
public static Deserialize(data: string): any
{
return JSON.parse(data, Helper.ReviveDateTime);
}
private static ReviveDateTime(key: any, value: any): any
{
if (typeof value === 'string')
{
let a = /\/Date\((\d*)\)\//.exec(value);
if (a)
{
return new Date(+a[1]);
}
}
return value;
}
}
You can see this approach for example here: JSON.parse Functionin the dateReviver example.
您可以在此处查看此方法的示例:dateReviver 示例中的JSON.parse 函数。
Hope this helps.
希望这可以帮助。
回答by Günter Z?chbauer
There is no way to know for TS/JS that this value is a date. It's a string and treated as such. Other data types are distinguishable but JSON doesn't provide any special support for date. You need to convert it manually.
对于 TS/JS,没有办法知道这个值是一个日期。它是一个字符串并被如此对待。其他数据类型是可区分的,但 JSON 不提供任何对日期的特殊支持。您需要手动转换它。
See for example this discussion how to transport and convert a date using JSON How do I format a Microsoft JSON date?
例如,请参阅此讨论如何使用 JSON 传输和转换日期如何格式化 Microsoft JSON 日期?
回答by lduburas
If usage of custom TypeScript transformer is possible, ts-transformer-datescould be used:
如果可以使用自定义 TypeScript 转换器,则可以使用ts-transformer-dates:
import { toDates } from 'ts-transformer-dates';
const value = {
"data": [
{
"comment": "3541",
"datetime": "2016-01-01"
}
]
};
export class Job {
constructor(comment:string, datetime:Date) {
this.comment = comment;
this.datetime = datetime;
}
comment:string;
datetime:Date;
}
console.log(toDates<{data:Job[]}>(value));
Output:
输出:
{ data: [ { comment: '3541', datetime: 2016-01-01T00:00:00.000Z } ] }

