JToken:获取原始/原始 JSON 值 [英] JToken: Get raw/original JSON value

查看:31
本文介绍了JToken:获取原始/原始 JSON 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从 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 禁用 DateTime 识别:

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

JObject.Parse() 需要 JsonSerializerSettings,因此请使用 反序列化对象.此设置最终会传播到 JsonReader.DateParseHandling.

There's no overload to JObject.Parse() that takes a JsonSerializerSettings, so use DeserializeObject. This setting eventually gets propagated to JsonReader.DateParseHandling.

Newtonsoft 相关文档:

Related Newtonsoft docs:

这篇关于JToken:获取原始/原始 JSON 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆