Converting JToken into .NET types with custom SerializerSettings

∥☆過路亽.° 提交于 2021-01-28 08:07:16

问题


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, stringJTokenMyType, 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!