问题
Json.NET separates the JSON parsing from the construction of .NET objects. In particular should
JsonConvert.DeserializeObject<MyType>(jsonString)
be the same as
JsonConvert.DeserializeObject<JToken>(jsonString).ToObject<MyType>()
The ToObject
method has no parameter that takes a SerializerSettings
though. So how do I specify JSON converters and related settings?
回答1:
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));
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);
(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.)
For more on DateTime
parsing see Serializing Dates in JSON. Sample fiddle here.
来源:https://stackoverflow.com/questions/54907568/converting-jtoken-into-net-types-with-custom-serializersettings