Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...