12

I'm having to perform some custom deserialization with JSON.NET and I just found that it's treating the key values in a JToken as case sensitive. Here's some code:

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
     JToken token = JToken.Load(reader);
     JToken version = token["version"];

     string ver = version.ToObject<string>();

     return new MyVersion(ver);
}

The version variable is null even though the json contains a version element at the top level, it's just in upper case:

{
    "VERSION" : "1.0",
    "NAME" : "john smith"
}

Is there any way to use JToken with case-insensitive keys? Or maybe another approach without JToken that lets me grab and deserialize individual properties?

EDIT:

Based on the comments I ended up doing this:

JObject token = JObject.Load(reader);
string version = token.GetValue("version", StringComparison.OrdinalIgnoreCase).ToObject<string>(serializer);
mhaken
  • 975
  • 4
  • 13
  • 27
  • Yes, they are. But see [JSON.NET JObject key comparison case-insensitive](https://stackoverflow.com/a/20475542) for a workaround. – dbc Apr 17 '18 at 20:16

2 Answers2

26

You can cast JToken to JObject and do this:

string ver = ((JObject)token).GetValue("version", StringComparison.OrdinalIgnoreCase)?.Value<string>();
Vanderlei Pires
  • 484
  • 5
  • 10
4

Convert JToken to JObject and use TryGetValue method of JObject in which you can specify String Comparision.

 var jObject = JToken.Load(reader) as JObject;
 JToken version;
 jObject.TryGetValue("version", StringComparison.OrdinalIgnoreCase, out version);
Kumar Waghmode
  • 489
  • 2
  • 17