JToken: get original / original JSON value

Is there a way to get the original JSON value with a JToken ?

Problem:

 var data = JObject.Parse(@"{ ""SimpleDate"":""2012-05-18T00:00:00Z"", ""PatternDate"":""2012-11-07T00:00:00Z"" }"); var value = data["SimpleDate"].Value<string>(); 

value now 05/18/2012 00:00:00 , but I need the original line 2012-05-18T00:00:00Z .

Is there any way to get this initial value? Also, I cannot change the way I create a JObject (for example, change the settings), because it is passed as a parameter to my class ...

(Ref: NJsonSchema Original Problem )

+7
json c #
source share
2 answers

You cannot get the original string, date strings are recognized and converted to DateTime structures inside JsonReader . You can see this if:

 Console.WriteLine(((JValue)data["SimpleDate"]).Value.GetType()); // Prints System.DateTime 

You can, however, extract dates in ISO 8601 format by following these steps:

 var value = JsonConvert.SerializeObject(data["SimpleDate"]); // value is "2012-05-18T00:00:00Z" 

This will always output JValue in a suitable JSON string format. Since your starting dates are in this format, this can satisfy your needs.

(Honestly, I'm surprised JValue.ToString() outputs dates in a format other than ISO, given that JObject.ToString() displays dates specified in ISO format.)

If you were able to change the settings while reading your JObject , you can use JsonSerializerSettings.DateParseHandling = DateParseHandling.None :

  var settings = new JsonSerializerSettings { DateParseHandling = DateParseHandling.None }; var data = JsonConvert.DeserializeObject<JObject>(@"{ ""SimpleDate"":""2012-05-18T00:00:00Z"", ""PatternDate"":""2012-11-07T00:00:00Z"" }", settings); var value = data["SimpleDate"].Value<string>(); Debug.WriteLine(value); // Outputs 2012-05-18T00:00:00Z 

There is no overload in JObject.Parse() that accepts JsonSerializerSettings , so you will need to use DeserializeObject . This parameter ultimately extends to JsonReader.DateParseHandling .

+7
source share

another approach - it will work - Regex

 SimpleDate(?:.*):(?:.*?)\"([0-9|-]{1,}T[0-9|:]+Z) 

it's a regex pattern to retrieve the data you are looking for - you just wanted a string, so here it is. this is not a JSON parsing approach, but it does retrieve the string.

here is an example of how it works

-2
source share

All Articles