JSON.NET JObject 键比较不区分大小写

JSON.NET JObject key comparison case-insensitive(JSON.NET JObject 键比较不区分大小写)
本文介绍了JSON.NET JObject 键比较不区分大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在使用 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 键比较不区分大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)
How to store delegates in a List(如何将代表存储在列表中)
How delegates work (in the background)?(代表如何工作(在后台)?)
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)