如何在newtonsoft.json中使用这个json路径C#

时间:2018-01-08 18:28:50

标签: c# .net json json.net jsonpath

我一直在构建一个应用程序,其中将从用户API提供JSON。它应该使用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这样的工具中,以下JSONPath查询可以正常工作,但是使用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 */ );

相反,我得到了例外:

  

属性'*'在JArray上无效。

如果我像这样执行JSONPath:

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属性的单个循环?

1 个答案:

答案 0 :(得分:2)

JSONPath - XPath for JSON所示,数组元素通配符的语法为idea.properties。因此,您的代码应如下所示:

[*]

这里我使用JToken.ToObject<T>()将每个数组元素直接反序列化为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(); ,而无需重新序列化为字符串。

示例工作.Net fiddle