Json.NET不区分大小写的属性反序列化 [英] Json.NET Case-insensitive Property Deserialization
问题描述
Json.NET将不区分大小写的属性反序列化"列为广告中的功能之一.我已经读到,将首先尝试匹配指定属性的大小写,如果找不到匹配项,则执行不区分大小写的搜索.但是,这似乎不是默认行为.请参见以下示例:
Json.NET lists "Case-insensitive property deserialization" as one of the advertised features. I have read that an attempt will first be made to match the case of the property specified and if a match is not found a case-insensitive search is performed. This does not appear to be the default behavior however. See the following example:
var result =
JsonConvert.DeserializeObject<KeyValuePair<int, string>>(
"{key: 123, value: \"test value\"}"
);
// result is equal to: default(KeyValuePair<int, string>)
如果更改了JSON字符串以匹配属性的大小写(键"和值"与键"和值"),那么一切都很好:
If the JSON string is altered to match the case of the properties ("Key" and "Value" vs "key" and "value") then all is well:
var result =
JsonConvert.DeserializeObject<KeyValuePair<int, string>>(
"{Key: 123, Value: \"test value\"}"
);
// result is equal to: new KeyValuePair<int, string>(123, "test value")
是否可以执行不区分大小写的反序列化?
Is there a way to perform to case-insensitive deserialization?
推荐答案
那是一个错误.
不区分大小写的属性反序列化是指Json.NET能够将名称为"Key"的JSON属性映射到.NET类的"Key"或"key"成员.
Case-insensitive property deserialization refers to Json.NET being able to map a JSON property with the name "Key" to either a .NET class's "Key" or "key" member.
错误是KeyValuePair需要其自己的JsonConverter,但是错过了不区分大小写的映射.
The bug is KeyValuePair requires its own JsonConverter but misses out of the case insensitive mapping.
以此为基础,并在读取JSON时将小写的键"和值"添加到case语句中.
Use that as a base and add the lower case "key" and "value" to the case statement when reading JSON.
这篇关于Json.NET不区分大小写的属性反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!