Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.NET Case-insensitive Property Deserialization

Tags:

c#

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

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?

like image 886
Phil Klein Avatar asked Jun 29 '12 17:06

Phil Klein


People also ask

Is JSON Net case sensitive?

Json does case sensitive JSON deserialization. Case sensitivity comes into play when a JSON string is being deserialized into an object.

Should JSON be case insensitive?

JSON is case-sensitive. SQL is case-insensitive, but names in SQL code are implicitly uppercase.

Is Jobject case sensitive?

Refer to this answer that this is wanted according the JSON-RPC spec (keys are case sensitive!).

Is StringEnumConverter case sensitive?

Jericho commented on Nov 25, 2017Up until Json.net v9, the StringEnumConverter class was case insensitive and it was changed in v10. Here's the discussion explaining why it was changed and here's the commit released in v10 that changed the behavior to case-sensitive.


1 Answers

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.

like image 77
James Newton-King Avatar answered Sep 20 '22 16:09

James Newton-King