c# - 在 Newtonsoft.Json.Linq.JObject 上运行表达式谓词

标签 c# json linq json.net jsonpath

我正在创建如下所示的 JObject 列表。我想使用查询表达式搜索集合。在下面的示例代码中,我使用 Jsonpath 查询来查找所有类型为 Buy 的头寸对象(枚举 Buy 的 int 值为 1 )

List<JObject> list = new List<JObject>();
list.Add(JObject.FromObject(new Position() { PositionType = PositionType.Buy, Investment = new Investment() { InvestmentCode = "AAPL" } }));
list.Add(JObject.FromObject(new Position() { PositionType = PositionType.Sell, Investment = new Investment() { InvestmentCode = "AAPL" } }));

var x = list.Find(j =>
{
    JToken token =  j.SelectToken("$[?(@.PositionType == 1)]");
    return token != null;
});

SelectToken 方法在谓词中返回 null。我不确定我是否使用了正确的方法。有没有一种方法可以在对象上评估谓词?

最佳答案

SelectTokens() documentation 没有很好地解释它或 JSONPath standard ,但 [?(script)] 运算符有争议地被定义为用于子对象的条件选择。这是因为 [?()] 运算符实际上是 script 运算符 的组合,嵌套在 child/subscript 运算符 中。来自standard :

Here is a complete overview and a side by side comparison of the JSONPath syntax elements with its XPath counterparts.

XPath    JSONPath    Description 
/        . or []     child operator 
[]       []          subscript operator. XPath uses it to iterate over element collections and for predicates. In Javascript and JSON it is the native array operator. 
[]       ?()         applies a filter (script) expression. 
n/a      ()          script expression, using the underlying script engine. 

[?()] 运算符标准显示的唯一示例是匹配数组内对象的属性,并返回这些对象。

因此,如果我使用 "$[?(@.PositionType == 1) 在 [{"PositionType": 1}] 上执行 SelectTokens() ]" 然后返回一个对象,但是在 {"PositionType": 1} 上执行此操作(正如您在 Find() 谓词中尝试执行的那样) 什么都不返回。

Json.NET 对标准的解释并不完全不同。以下是尝试将 {"PositionType": 1}"$[?(@.PositionType == 1)]"$ 进行匹配的结果。 .[?(@.PositionType == 1)] 使用各种 JSONPath 解析器:

你可以 report an issue关于 Json.NET 的行为,但考虑到实现之间的不一致,它可能无法得到解决。与此时的 XPath 相比,JSONPath 标准的定义可能不够明确且不够稳定,无法满足您的需求。

另见 Newtonsoft JSON SelectToken to get data from multiple parts of JSON document?How to select JToken based on multiple name candidates in JSONPath? .

关于c# - 在 Newtonsoft.Json.Linq.JObject 上运行表达式谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39000602/

相关文章:

c# - 在没有 ToList() 的带有 linq 的 foreach 中时数据库被锁定

c# - StartsWith Windows Server 2012 中的更改

c# - HttpListener 将数据写入响应输出流

javascript - Vue.js 不支持 HTML 文件中的外部 JSON

java - Fasterxml ObjectMapper 不排除 JSON 中的字段

c# - 如何在 linq to NHibernate 中使用 select for associations

c# - 如何在更改数据库后保存数据集?

c# - 如何卸载 .NET Core 中的程序集/使其可收集?

javascript - 如何将json数据动态插入到html元素中

sql - 简单的 Linq 问题 : How to select more than one column?