Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement Custom DateTime Converter with JSON.NET

Tags:

json

c#

json.net

I'm having troubles parsing the below JSON when using a Date Time converter. I understand the "-" and "at" cause problems, but this is the JSON I have in a response and do not have 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 is:

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 have tried deserializing it as shown below, even by removing the "at" in the Date Time string, but I still get a "string is not in the correct format" exception from JSON.NET. I am having a hard time figuring out other ways of resolving. 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);
like image 845
YnotDraw Avatar asked Jan 13 '15 17:01

YnotDraw


1 Answers

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 debug it at ReadJson and parse date there - it should be easier now.

like image 126
fex Avatar answered Oct 28 '22 17:10

fex