Reputation: 4506
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();
Upvotes: 51
Views: 34779
Reputation: 23269
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
Upvotes: 144
Reputation: 6038
c# allows you to use dictionaries with keys that are case insensitive, so a workaround I've used is to convert the JObject to a dictionary with StringComparer.CurrentCultureIgnoreCase
set, like so:
JObject json = (JObject)JsonConvert.DeserializeObject(ptString);
Dictionary<string, object> d = new Dictionary<string, object>(json.ToObject<IDictionary<string, object>>(), StringComparer.CurrentCultureIgnoreCase);
String f = d["FROM"].ToString();
Upvotes: 17