Implementing Custom DateTime Converter with JSON.NET

I am having trouble parsing below JSON when using the Date Time converter. I understand the "-" and "on" problems, but this is the JSON I received in response and I have no control over it.

"[{\"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\"}]"

      

My model:

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

      

I tried to deserialize it like below, even removing the "at" in the Date Time string, but I still get a "string not in correct format" exception from JSON.NET. I find it difficult to identify other ways to solve the problem. Any help would be appreciated!

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

      

+3


source to share


1 answer


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

      



Try debugging it on ReadJson and parsing there - it should be easier now.

+9


source







All Articles