Search code examples
c#json.net

Jtoken containing DateTime tostring unexpected behaviour


I have this json:

{
  "sku": "articlenumber",
  "lastModified": "2022-05-06T10:07:23.934Z",
  "quantity": 20
}

I have to send the exact value of "lastModified". As I don't have to do any operations on this value I decided to store it in a string. The problem is casting the JToken to string gives me a completely different formatting:

string foo = (string)json["lastModified"]
/// 05/06/2022 10:07:23

How can I get the actual recieved raw string out of the json?

what I already tried: parsing the data into a datetime object and serializing with custom settings like so

JsonSerializerSettings settings = new JsonSerializerSettings
{  
    DateFormatString = "yyyy-MM-dd'T'HH:mm:ss.fffZ",
    DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind
};

This gives me a correctly formatted string but zeroes the miliseconds.

/// "2022-05-06T10:07:23.000Z"

Solution

  • var json = "{\"sku\": \"articlenumber\",\"lastModified\": \"2022-05-06T10:07:23.934Z\", \"quantity\": 20}";
    var settings = new JsonSerializerSettings { DateParseHandling = DateParseHandling.None };
    var data = JsonConvert.DeserializeObject<JObject>(json, settings);
    var result = data.Value<string>("lastModified");
    
    • The trick here is the DateParseHandling.None
    • The weird part is to use DeserializeObject to get JObject

    You can use data["lastModified"].Value<string>() as well if you wish.