问题描述
Json.NET将JSON解析与.NET对象的构造分开.特别应该
Json.NET separates the JSON parsing from the construction of .NET objects. In particular should
JsonConvert.DeserializeObject<MyType>(jsonString)
与
JsonConvert.DeserializeObject<JToken>(jsonString).ToObject<MyType>()
ToObject
方法没有带SerializerSettings
的参数.那么如何指定JSON转换器和相关设置?
The ToObject
method has no parameter that takes a SerializerSettings
though. So how do I specify JSON converters and related settings?
推荐答案
如果您已经将JSON解析为JToken
层次结构,则可以使用 JToken.ToObject<T>(JsonSerializer)
以使用转换器反序列化为所需的类型:
If you have already parsed your JSON into a JToken
hierarchy, you can use JToken.ToObject<T>(JsonSerializer)
to deserialize to your desired type using your converters:
var settings = new JsonSerializerSettings
{
Converters = { new MyTypeConverter() },
// Other settings as required.
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
};
var myType = jToken.ToObject<MyType>(JsonSerializer.CreateDefault(settings));
请注意,Json.NET在字符串标记化过程中处理DateTime
和浮点识别,因此,如果将JSON反序列化分为两个阶段,即string
⇒JToken
⇒MyType
,则日期字符串和十进制数可能会被过早地解析和识别.最初解析JSON和/或推迟日期识别时,您可能需要指定适当的设置,如下所示:
Note that Json.NET handles DateTime
and floating-point recognition during string tokenization, so if you split your JSON deserialization into two stages, string
⇒ JToken
⇒ MyType
, then date strings and decimals may get parsed and recognized prematurely. You may need to specify appropriate settings while initially parsing your JSON and/or defer date recognition like so:
var parseSettings = new JsonSerializerSettings
{
DateParseHandling = DateParseHandling.None, // Defer date/time recognition until later.
FloatParseHandling = FloatParseHandling.Decimal, // Or Double if required.
};
var jToken = JsonConvert.DeserializeObject<JToken>(jsonString, parseSettings);
(相反,当不使用中间JToken
表示形式而直接从字符串反序列化为POCO时,序列化程序可以将提示"传递给 JsonTextReader
标记生成器,用于确定某些原始标记是否应解释为日期,小数或使用 ReadType
枚举.因此,枚举是内部的牛顿软件.)
(In contrast, when deserializing directly from a string to a POCO without an intermediate JToken
representation, the serializer can pass "hints" to the JsonTextReader
tokenizer as to whether certain primitive tokens should be interpreted as dates, decimals or whatever by using the ReadType
enum. Thus enumeration is, however, internal to Newtonsoft.)
有关DateTime
解析的更多信息,请参见 用JSON序列化日期 .样本小提琴此处.
For more on DateTime
parsing see Serializing Dates in JSON. Sample fiddle here.
这篇关于使用自定义SerializerSettings将JToken转换为.NET类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!