JToken:获取原始/原始JSON值 [英] JToken: Get raw/original JSON value
问题描述
是否可以从JToken
获取原始/原始JSON值?
Is there a way to get the raw/original JSON value from a JToken
?
问题:
var data = JObject.Parse(@"{
""SimpleDate"":""2012-05-18T00:00:00Z"",
""PatternDate"":""2012-11-07T00:00:00Z""
}");
var value = data["SimpleDate"].Value<string>();
value
现在是05/18/2012 00:00:00
,但是我需要原始字符串2012-05-18T00:00:00Z
.
The value
is now 05/18/2012 00:00:00
but I need the original string 2012-05-18T00:00:00Z
.
有没有办法获得这个原始值?另外,我不能更改JObject
的创建方式(例如更改设置),因为它会作为参数传递给我的课程...
Is there a way to get this original value? Also, I cannot change the way how the JObject
is created (e.g. change settings), because it is passed as parameter into my class...
(参考:原始的NJsonSchema问题)
推荐答案
您无法获取原始字符串,可以识别日期字符串并将其转换为JsonReader
本身.如果您这样做,可以看到以下内容:
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
但是,您可以执行以下操作,以 ISO 8601 格式提取日期:
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"
这将始终以JSON合适的字符串格式输出JValue
.由于您的原始日期采用这种格式,因此可以满足您的需求.
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.
(老实说,我很惊讶 JValue.ToString()
输出日期以非ISO格式,假设 JObject.ToString()
会输出包含日期以ISO格式).
(Honestly, I'm surprised JValue.ToString()
outputs dates in non-ISO format, given that JObject.ToString()
does output contained dates in ISO format.)
如果您能够在阅读JObject
时更改设置,则可以使用 JsonSerializerSettings.DateParseHandling = DateParseHandling.None
:
If you were able to change settings while reading your JObject
, you could 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
JObject.Parse()
不会超载,它需要DeserializeObject
.此设置最终会传播到 JsonReader.DateParseHandling
.
这篇关于JToken:获取原始/原始JSON值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!