使用JSON.NET实现自定义DateTime转换器

时间:2015-01-13 17:50:14

标签: c# json json.net

使用日期时间转换器时,我在解析下面的JSON时遇到了麻烦。我理解" - "和" at"导致问题,但这是我在响应中的JSON,并且无法控制它。

"[{\"Desc\":\"Unacceptable Signal\",\"Station\":\"Test\",\"When\":\"Tuesday - 5/18/10 at 3:34 PM\"},{\"Desc\":\"Low Battery\",\"Station\":\"Test Unit (21261)\",\"When\":\"Wednesday - 3/30/11 at 12:34 AM\"}]"

我的模特是:

public class CurrentAlarms
    {
        public string Desc { get; set; }
        public string Station { get; set; }
        public DateTime When { get; set; }

        public CurrentAlarms() { }

        public CurrentAlarms(string desc, string station, DateTime when)
        {
            Desc = desc;
            Station = station;
            When = when;
        }
    }

我已尝试将其反序列化,如下所示,即使删除" at"在日期时间字符串中,但我仍然得到一个"字符串格式不正确"来自JSON.NET的例外。我很难找到其他解决方法。任何帮助将不胜感激!

json = json.Replace(" at ", " ");

var format = "dddd MM/dd/yy h:mm tt";
var dateTimeConverter = new IsoDateTimeConverter {DateTimeFormat = format};

var result = JsonConvert.DeserializeObject<ObservableCollection<CurrentAlarms>>(json, dateTimeConverter);

1 个答案:

答案 0 :(得分:13)

public class CurrentAlarms
{
    public string Desc { get; set; }
    public string Station { get; set; }
    [JsonConverter(typeof(InvalidDataFormatJsonConverter))]
    public DateTime When { get; set; }

    public CurrentAlarms() { }

    public CurrentAlarms(string desc, string station, DateTime when)
    {
        Desc = desc;
        Station = station;
        When = when;
    }
}

class InvalidDataFormatJsonConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        // implement in case you're serializing it back
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
        JsonSerializer serializer)
    {
        var dataString = (string) reader.Value;
        DateTime date = parseDataString;             

        return date;
    }

    public override bool CanConvert(Type objectType)
    {
        return true;
    }
}

尝试在ReadJson上调试它并在那里解析日期 - 现在应该更容易了。