45

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();
4

2 回答 2

130

这应该有效:

var json = @"{UPPER: 'value'}";
var jObj = JObject.Parse(json);
var upper = jObj.GetValue("upper", StringComparison.OrdinalIgnoreCase)?.Value<string>();

Console.WriteLine(upper); // value
于 2013-12-09T16:26:55.983 回答
14

c# 允许您使用不区分大小写的键的字典,因此我使用的解决方法是将 JObject 转换为带有StringComparer.CurrentCultureIgnoreCase集合的字典,如下所示:

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();
于 2013-06-26T22:57:54.377 回答