Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

c# - Json.NET Case-insensitive Property Deserialization

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>)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That's a bug.

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.

The bug is KeyValuePair requires its own JsonConverter but misses out of the case insensitive mapping.

https://github.com/JamesNK/Newtonsoft.Json/blob/fe200fbaeb5bad3852812db1e964473e1f881d93/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs

Use that as a base and add the lower case "key" and "value" to the case statement when reading JSON.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...