Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.NET JToken Keys Are Case Sensitive?

Tags:

json

c#

json.net

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);
like image 274
mhaken Avatar asked Apr 17 '18 19:04

mhaken


People also ask

Is JSON Net case sensitive?

JSON is case sensitive to both field names and data. So is N1QL. JSON can have the following. N1QL will select-join-project each field and value as a distinct field and value.

What is JToken in JSON?

JToken is the abstract base class of JObject , JArray , JProperty , and JValue , which represent pieces of JSON data after they have been parsed. JsonToken is an enum that is used by JsonReader and JsonWriter to indicate which type of token is being read or written.

What is the difference between JToken and JObject?

JToken is the base class for all JSON elements. You should just use the Parse method for the type of element you expect to have in the string. If you don't know what it is, use JToken, and then you'll be able to down cast it to JObject, JArray, etc. In this case you always expect a JObject, so use that.

What is JToken used for?

Represents an abstract JSON token. The JToken type exposes the following members. Gets a comparer that can compare two tokens for value equality.


2 Answers

You can cast JToken to JObject and do this:

string ver = ((JObject)token).GetValue("version", StringComparison.OrdinalIgnoreCase)?.Value<string>();
like image 142
Vanderlei Pires Avatar answered Oct 03 '22 13:10

Vanderlei Pires


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);
like image 21
Kumar Waghmode Avatar answered Oct 03 '22 14:10

Kumar Waghmode