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);
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.
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.
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.
Represents an abstract JSON token. The JToken type exposes the following members. Gets a comparer that can compare two tokens for value equality.
You can cast JToken to JObject and do this:
string ver = ((JObject)token).GetValue("version", StringComparison.OrdinalIgnoreCase)?.Value<string>();
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With