Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

How to get Date object from json Response in typescript

Here is my 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 Date but it is string. Shouldn't it cast to Date object? What am i missing here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

@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).

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 Function in the dateReviver example.

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...