MonkeyWrench
MonkeyWrench

Reputation: 1839

C# Newtonsoft JsonConvert can't deserializeDateTime properly

We have a MVC.Core project where we're having problems deserializing a DateTime value from a string into a DateTime property.

Here's an example:

public class TestClass
{
    public RecordStatus RecordStatus { get; set; } = RecordStatus.Active;

    [System.ComponentModel.Browsable(false)]
    public DateTime CreatedOn { get; private set; }
}


    string s = @"{""recordStatus"":""Active"",""createdOn"":""2018-03-02T21:39:22.075Z""}";

    JsonSerializerSettings jsonSettings = new JsonSerializerSettings()
    {
        DateFormatString = "yyyy-MM-ddTHH:mm:ss.FFFZ",
        DateTimeZoneHandling = DateTimeZoneHandling.Utc,
        MissingMemberHandling = MissingMemberHandling.Ignore
    };

    TestClass psm = JsonConvert.DeserializeObject<TestClass>(s, jsonSettings);

The value of psm.CreatedOn is being set to

{1/1/0001 12:00:00 AM}

I've tried a bunch of different combination of values for the serializer settings with no luck. What am I missing here? I know I'm missing something obvious, but it's on of those days.

Thanks

Upvotes: 0

Views: 445

Answers (2)

Hussein Salman
Hussein Salman

Reputation: 8236

public class TestClass
{
    public RecordStatus RecordStatus { get; set; } = RecordStatus.Active;

    [System.ComponentModel.Browsable(false)]
    public DateTime CreatedOn { get; set; }
}

Remove the private access modifier from the setter for the CreatedOn property

Upvotes: 1

Pete Garafano
Pete Garafano

Reputation: 4913

The problem here isn't the format string, that is just fine (as we can see here):

Console.WriteLine(DateTime.ParseExact("2018-03-02T21:39:22.075Z","yyyy-MM-ddTHH:mm:ss.FFFZ", CultureInfo.InvariantCulture));

Yields:

02-Mar-18 4:39:22 PM

The issue is actually the private setter on CreatedOn. If you remove that everything works. In fact, it works with the default serializer settings, so there is no need to do anything with that format string.

If you are set on having a private setter for that field, then I would suggest looking into something like this to make Json.NET use the private setter.

Upvotes: 2

Related Questions