Custom JSON deserializer in JavaScript for the Date object

The date data when appears in a string may be stored in different formats. E.g. Date(...) or the RFC 8601 form.

When we need to do some custom adjustments to the serialization process, add a method to the JSON.parse like this:


export class JsonParseHelper
{
    public static Deserialize(data: string): any
    {
        return JSON.parse(data, JsonParseHelper.ReviveDateTime);
    }
 
    private static ReviveDateTime(key: any, value: any): any 
    {
        if (typeof value === 'string')
        { 
            if (moment(value, moment.ISO_8601, true).isValid()) {
              return moment(value, moment.ISO_8601, true).toDate();
            }
        }
 
        return value;
    } 
} 

Post a Comment

Previous Post Next Post