Json.DeserializeObject不适用于DateTime成员

时间:2019-08-08 12:38:21

标签: c# json datetime json.net

我有一个包含两个DateTimes的类。该类还包含两种方法,一种用于保存设置,另一种用于读取设置。

class DateTimes
{
    private DateTime dateTime1;
    private DateTime dateTime2;

    public DateTime DateTime1
    {
        get => dateTime1;
        private set => dateTime1;
    }

    public DateTime DateTime2
    {
        get => dateTime2;
        private set => dateTime2;
    }

    public void ReadSettings()
    {
        //settingsString is of type Object. I am pretty sure that is not the problem, as I've already checked it many times.

        DateTimes DateTimesStorage = JsonConvert.DeserializeObject<DateTimes>(settingString as string ?? "");

        this.DateTime1 = DateTimesStorage?.DateTime1;
        this.DateTime2 = DateTimesStorage?.DateTime2;
    }

    public void SaveSettings()
    {
        settingString = JsonConvert.SerializeObject(this);
    }
}

“ settingsString”始终仅由上述两种方法处理,因此不应有干扰。当我检查DateTimesStorage时进行调试时,其成员始终等于(new DateTime()),而不是保存在Json中的成员。

因此问题不应该在SaveSettings()中正常运行,而在ReadSettings()中,因为JsonConvert.DeserializeObject似乎无法识别两个日期时间,而只是创建空日期时间。

0 个答案:

没有答案