I want to parse a DateTime from a JSON stream.
The pattern for the Date is YYYY/MM/DD.
How can I set this custom format on the settings of the Serializer or using the DateParseHandling?
Simply set the DateFormatString on the JsonSerializer to the format you need. Json.Net uses the same format specifiers as the .NET framework.
Here is an example:
class Program
{
static void Main(string[] args)
{
string json = @"{ ""date"" : ""2014/10/07"" }";
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
using (StreamReader sr = new StreamReader(ms))
using (JsonTextReader jtr = new JsonTextReader(sr))
{
JsonSerializer ser = new JsonSerializer();
ser.DateFormatString = "yyyy/MM/dd";
Foo foo = ser.Deserialize<Foo>(jtr);
Console.WriteLine(foo.Date.ToLongDateString());
}
}
}
class Foo
{
public DateTime Date { get; set; }
}
Example output:
Tuesday, October 07, 2014