2

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?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Nitpick: in C# strings are UTF16 and not UTF8
@ChrisWue True, C# strings use UTF-16 internally; however, StreamReader expects UTF-8 by default (doc), which is why I chose to use UTF-8 encoding here. I suppose I could have gotten the bytes as UTF-16 and then passed the UTF-16 Encoding to the constructor of the StreamReader, but that just makes the example code more complicated for not much benefit. The OP is probably getting his JSON from some other kind of Stream that has UTF-8 encoded characters, in which case constructing a StreamReader with UTF-16 would be incorrect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.