如何在 newtonsoft.json C# 中采用此 json 路径

How take this json path in newtonsoft.json C#

我一直在构建一个应用程序,其中 JSON 将由用户 API 提供。它应该使用 JSONPath 从 JSON 读取数据并保留所选部分。我正在尝试使用 Json.Net (Newtonsoft) 来做到这一点。以下JSON为范例:

{
  // other properties here and different structure here

  "Data": [
    {
      "Code": "625087",
      "Name": "Customer Name",
      "Email": "test@hfgidfgd.com"
    },
    {
      "Code": "625087",
      "Name": "Customer Name",
      "Email": "test@hfgidfgd.com"
    },
    {
      "Code": "625087",
      "Name": "Customer Name",
      "Email": "test@hfgidfgd.com"
    }
  ],

  // other properties here and different structure here
}

我想使用 JSONPath 提取由 Data 属性 内容呈现的数组,并将其转换为 List<Dictionary<string, object>> 以在我的应用程序中进行操作。

jsonpath.com 等工具中,以下 JSON 路径查询可以正常工作,但使用 Newtonsoft 则不行:

// get that json
string content = GetJson();

var jo = JObject.Parse(content);

var jsonPath = "$..Data.*";
var jsonPathResult = jo.SelectTokens(jsonPath, true /* to get error when it is not found */ );

相反,我得到了异常:

Property '*' not valid on JArray.

如果我像这样执行 JSON路径:

var jsonPath = "$..Data"; // same for just: "Data"
var jsonPathResult = jo.SelectTokens(jsonPath);

我必须用两个嵌套的 foreach 循环结果,我认为这不是一个优雅的解决方案:

var result = new List<Dictionary<string, object>>();

foreach (var jsonResult in jsonPathResult)
{
    foreach (var item in jsonResult)
    {
        var fields = JsonConvert.DeserializeObject<Dictionary<string, object>>(item.ToString());

        // some adjusts on the fields dictionary will be applied here...

        result.Add(fields);
    }
}

有没有什么办法可以得到只用Data属性的内容单循环的结果?

JSONPath - XPath for JSON所示,数组元素通配符的语法是[*]。因此你的代码应该是这样的:

var jsonPath = "$..Data[*]";
var result = jo.SelectTokens(jsonPath, true /* to get error when it is not found */ )
    .Select(o => o.ToObject<Dictionary<string, object>>())
    .ToList();

这里我使用 JToken.ToObject<T>() 将每个数组元素直接反序列化为 Dictionary<string, object>> 而无需重新序列化为字符串。

工作示例 .Net fiddle