Jonathan Jonathan - 13 days ago 5
C# Question

Json.NET ToObject Date Serialization Format

I'm trying to set a custom date format when using Newtonsoft.Json ToObject to convert from JSON to my custom Object but trying different ways I can't get it to alter the date format at all.

public class CustomObject
{
public string DateRecordedString { get; set; }
}

static void Main(string[] args)
{
string jsonResult = "[{\"daterecordedstring\":\"2016-11-21T08:24:42\"}]";
JToken jtokenResult = JToken.Parse(jsonResult);

var objectResult1 = jtokenResult.ToObject<CustomObject[]>();
Console.WriteLine(objectResult1.First().DateRecordedString); // -> 11/21/2016 08:24:42

var objectResult2 = jtokenResult.ToObject<CustomObject[]>(new JsonSerializer { DateParseHandling = DateParseHandling.None });
Console.WriteLine(objectResult2.First().DateRecordedString); // -> 11/21/2016 08:24:42

var objectResult3 = jtokenResult.ToObject<CustomObject[]>(new JsonSerializer { DateFormatString = "yyyy-M-d" });
Console.WriteLine(objectResult3.First().DateRecordedString); // -> 11/21/2016 08:24:42

}


How can I get ToObject to return a date in the format I want (or leave it unchanged)?

Answer

Seems like JToken.Parse is doing some type conversion before you do.

As answered in Do not convert JToken date time string as DateTime

void Main()
{
     string jsonResult = "[{\"daterecordedstring\":\"2016-11-21T08:24:42\"}]";

    using (var sr = new StringReader(jsonResult))
    using (var jr = new JsonTextReader(sr) { DateParseHandling = DateParseHandling.None })
    {
        var j = JToken.ReadFrom(jr);
        Console.WriteLine(j["value"].ToString()); // prints '2016-11-21T08:24:42'
    }
}

full kudos to user5090812

Comments