Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.NET JObject key comparison case-insensitive

Tags:

json

c#

json.net

I'm using Newtonsoft Json.net to parse the JSON string. I convert the string into the JObject. When access the value of the element by the key, I want to the comparison is case-insensitive. In the code below, I use "FROM" as the key. I want it returns string "1" at the line json["FROM"].ToString(). But it fails. Is it possible to make the code below work?

String ptString = "{from: 1, to: 3}"; var json = (JObject)JsonConvert.DeserializeObject(ptString);  String f = json["FROM"].ToString(); 
like image 805
Jeffrey Avatar asked Aug 21 '12 13:08

Jeffrey


People also ask

Is JObject case sensitive?

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

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.

What is JObject and JToken?

The JToken hierarchy looks like this: JToken - abstract base class JContainer - abstract base class of JTokens that can contain other JTokens JArray - represents a JSON array (contains an ordered list of JTokens) JObject - represents a JSON object (contains a collection of JProperties) JProperty - represents a JSON ...

What is JToken in C#?

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.


1 Answers

This should work:

var json = @"{UPPER: 'value'}"; var jObj = JObject.Parse(json); var upper = jObj.GetValue("upper", StringComparison.OrdinalIgnoreCase)?.Value<string>();  Console.WriteLine(upper); // value 
like image 171
Gian Marco Avatar answered Oct 11 '22 18:10

Gian Marco