JToken: Get raw/original JSON value
You cannot get the original string, date strings are recognized and converted to DateTime
structs inside the JsonReader
itself. You can see this if you do:
Console.WriteLine(((JValue)data["SimpleDate"]).Value.GetType()); // Prints System.DateTime
You can, however, extract the dates in ISO 8601 format by doing:
var value = JsonConvert.SerializeObject(data["SimpleDate"]);
// value is "2012-05-18T00:00:00Z"
This will always output a JValue
in a JSON-appropriate string format. Since your original dates are in this format, this may meet your needs.
(Honestly, I'm surprised JValue.ToString()
outputs dates in non-ISO format, given that JObject.ToString()
does output contained dates in ISO format.)
If you were able to change you settings while reading your JObject
, you could use JsonSerializerSettings.DateParseHandling = DateParseHandling.None
to disable DateTime
recognition:
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's no overload to JObject.Parse()
that takes a JsonSerializerSettings
, so use DeserializeObject
. This setting eventually gets propagated to JsonReader.DateParseHandling
.
Related Newtonsoft docs:
- Json.NET interprets and modifies ISO dates when deserializing to JObject #862
- Serializing Dates in JSON.
What is going on with the parser of Json.NET (Newtonsoft) with timestamp strings?
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);
Find JToken if value matches with a given pattern
You can use Descendants()
method here, get all properties and filter them by checking __
string in value
var json = JObject.Parse(jsonString);
var result = json.Descendants().OfType<JProperty>().Where(p =>
p.Value.Type == JTokenType.String && p.Value.Value<string>().Contains("__"));
Given a JSON value, how do I get the parent's sibling value?
You may flatten inner item
array using SelectMany
method into one sequence (since outer item
is also an array), then get name
and raw
values directly by key
var jObject = JObject.Parse(jsonString);
var innerItems = jObject["item"]?.SelectMany(t => t["item"]);
foreach (var item in innerItems)
{
var name = item["name"];
var raw = item["url"]?["raw"];
}
Converting JSON into class changes string value. Bug in JSON.NET?
I think that's because you're using the standard JObject.Parse, which 'thinks' that these values are dates (and then call a ToString() on them when you do the .ToObject()).
Try this:
var foo = JsonConvert.DeserializeObject<Test>(content);
Doing this, the deserializer will know which is the target type of every property, I guess.
JsonConvert is a static class inside Newtonsoft.Json .
Related Topics
Best Practice to Make a Multi Language Application in C#/Winforms
Using Case/Switch and Gettype to Determine the Object
What's the New C# Await Feature Do
Console.Writeline and Generic List
Get Property Name and Type Using Lambda Expression
Custom App.Config Section with a Simple List of "Add" Elements
Don't Stop Debugger at That Exception When It's Thrown and Caught
Regex to Get Number Only from String
How to Run Visual Studio Without Plugin and All Third Party Feature
Restrict Access to a Specific Controller by Ip Address in ASP.NET MVC Beta
Comparing Strings with Tolerance
How to Instantiate a Dbcontext in Ef Core
Single App.Config Multi-Project C#
Async Process Start and Wait for It to Finish
Hashtable with Multidimensional Key in C#
Wpf: How to Override Part of a Controltemplate Without Redefining the Whole Style