programing

타이프스크립트의 json Response에서 날짜 개체를 가져오는 방법

starjava 2023. 3. 28. 20:32
반응형

타이프스크립트의 json Response에서 날짜 개체를 가져오는 방법

제 아들입니다.

{
  "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;
}

쿼리:

getJobs() {
        return this._http.get(jobsUrl)
            .map((response:Response) => <Job[]>response.json().data)
}

문제는 에 캐스팅을 한 후Job[]나는 기대한다datetime될 성질Date스트링이에요.Date 객체에 캐스팅해야 하지 않나요?내가 뭘 놓쳤지?

@Gunter가 맞습니다.덧붙이고 싶은 것은 json 오브젝트의 날짜 속성을 문자열이 아닌 날짜로 유지하는 방법뿐입니다(참조된 게시물에서는 이 방법을 쉽게 알 수 없습니다).

제 시도는 다음과 같습니다.

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;
    }
}

예를 들어 dateReviver의 예에서 JSON.parse Function을 확인할 수 있습니다.

이게 도움이 됐으면 좋겠다.

TS/J의 경우 이 값이 날짜임을 알 수 없습니다.그것은 끈이고 그렇게 취급된다.다른 데이터 유형은 구분할 수 있지만 JSON은 날짜를 특별히 지원하지 않습니다.수동으로 변환해야 합니다.

예를 들어 JSON을 사용하여 날짜를 전송 및 변환하는 방법에 대한 자세한 내용은 Microsoft JSON 날짜를 포맷하려면 어떻게 해야 합니까?를 참조하십시오.

커스텀 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));

출력:

{ data: [ { comment: '3541', datetime: 2016-01-01T00:00:00.000Z } ] }

날짜를 전달하기 위한 문자열 속성(dateStr이라고 함)과 변환 후 데이터 개체를 유지하기 위한 날짜 속성(dateVal이라고 함)의 두 가지 속성을 사용하여 이를 달성할 수 있습니다.

그리고 컨스트럭터에서는 다음과 같은 작업을 간단하게 수행할 수 있습니다.dateVal = new Date(dateStr).

언급URL : https://stackoverflow.com/questions/35917808/how-to-get-date-object-from-json-response-in-typescript

반응형