从版本 8.0.2 开始,这在 Json.NET 中尚未实现。
JSONPath 属性名称匹配是通过两个类完成的:FieldFilter https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Linq/JsonPath/FieldFilter.cs对于简单的名称匹配,以及ScanFilter https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Linq/JsonPath/ScanFilter.cs用于递归搜索。FieldFilter
有以下代码,其中o
is a JObject
:
JToken v = o[Name];
if (v != null)
{
yield return v;
}
内部JObject https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Linq/JObject.cs uses a JPropertyKeyedCollection https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Linq/JPropertyKeyedCollection.cs保存其属性,这又使用以下比较器进行属性名称查找:
private static readonly IEqualityComparer<string> Comparer = StringComparer.Ordinal;
因此它区分大小写。相似地,ScanFilter
has:
JProperty e = value as JProperty;
if (e != null)
{
if (e.Name == Name)
{
yield return e.Value;
}
}
这也是区分大小写的。
中没有提到不区分大小写的匹配JSONPath 标准 http://goessner.net/articles/JsonPath/所以我认为你想要的东西根本无法开箱即用。
作为解决方法,您可以为此添加自己的扩展方法:
public static class JsonExtensions
{
public static IEnumerable<JToken> CaseSelectPropertyValues(this JToken token, string name)
{
var obj = token as JObject;
if (obj == null)
yield break;
foreach (var property in obj.Properties())
{
if (name == null)
yield return property.Value;
else if (string.Equals(property.Name, name, StringComparison.OrdinalIgnoreCase))
yield return property.Value;
}
}
public static IEnumerable<JToken> CaseSelectPropertyValues(this IEnumerable<JToken> tokens, string name)
{
if (tokens == null)
throw new ArgumentNullException();
return tokens.SelectMany(t => t.CaseSelectPropertyValues(name));
}
}
然后将它们与标准链接在一起SelectTokens
调用,例如:
var root = new { Array = new object[] { new { maxAppVersion = "1" }, new { MaxAppVersion = "2" } } };
var json = JToken.FromObject(root);
var tokens = json.SelectTokens("Array[*]").CaseSelectPropertyValues("maxappversion").ToList();
if (tokens.Count != 2)
throw new InvalidOperationException(); // No exception thrown
(相关地,请参阅 Json.NET 问题提供一种进行区分大小写的属性反序列化的方法 https://github.com/JamesNK/Newtonsoft.Json/issues/815它请求区分大小写的合同解析器以与 LINQ-to-JSON 的区分大小写保持一致。)