3
static void Main(string[] args)
{
    string someJsonString = "{\"time\": \"2021-02-24T13:15:43Z\"}";
    JObject someJsonObject = JObject.Parse(someJsonString);          
    string time = someJsonObject.GetValue("time").Value<string>();
    Console.WriteLine(time);
    Console.ReadLine();
}

[Using Newtonsoft.Json version 12.0.3]

Why is the printed result is 02/24/2021 13:15:43 when it should be 2021-02-24T13:15:43Z, I just need the value as a string ... what is going on?

Rashik Hasnat
  • 318
  • 4
  • 14
Green Fire
  • 720
  • 1
  • 8
  • 21

1 Answers1

6

JSON.Net will automatically parse a date formatted string into a DateTime object. If you want to prevent this, you either need to use a concrete class:

public class Foo
{
    public string Time { get; set; }
}

And deserialise like this:

var f = JsonConvert.DeserializeObject<Foo>(someJsonString);

Or if you really need a JObject, you can use a proper JsonReader object so you can configure how the parsing works, for example:

using var stringReader = new StringReader(someJsonString);
using var reader = new JsonTextReader(stringReader);
reader.DateParseHandling = DateParseHandling.None;
JObject someJsonObject = JObject.Load(reader);
DavidG
  • 113,891
  • 12
  • 217
  • 223