Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading