问题描述
我正在使用 Newtonsoft Json.net 来解析 JSON 字符串.我将字符串转换为 JObject.当通过键访问元素的值时,我希望比较不区分大小写.在下面的代码中,我使用FROM"作为键.我希望它在 json["FROM"].ToString() 行返回字符串1".但它失败了.是否可以使下面的代码工作?
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();
推荐答案
c# 允许您使用不区分大小写的键的字典,因此我使用的解决方法是使用 StringComparer 将 JObject 转换为字典.CurrentCultureIgnoreCase
设置,像这样:
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();
这篇关于JSON.NET JObject 键比较不区分大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!