2009年发布的
query的答案是使用一个新功能JObject.SelectToken,它应该提供类似XPath的功能.我现在使用JSON.NET 4.5 R11和SelectToken方法可用.
但是我找不到关于要传递给SelectToken函数的路径字符串的文档(基本上是语法).
下面的代码生成一个Json字符串,我想在其上执行类似Xpath的方法(即据我所知SelectToken)
IList branches = new ArrayList(); IList employees = new ArrayList(); employees.Add(new { EmpId = 1,Name = "Name1" }); employees.Add(new { EmpId = 2,Name = "Name2" }); employees.Add(new { EmpId = 3,Name = "Name3" }); IList employees2 = new ArrayList(); employees2.Add(new { EmpId = 4,Name = "Name1" }); employees2.Add(new { EmpId = 5,Name = "Name5" }); branches.Add(new { BranchName = "Branch1",Employees = employees }); branches.Add(new { BranchName = "Branch2",Employees = employees }); string json = JsonConvert.SerializeObject(branches); var branchesDeserialised = JsonConvert.DeserializeAnonymousType(json,new[] { new { BranchName = "",Employees = new[] { new { EmpId = 0,Name = "" } } } }); JArray ja = JArray.Parse(json); var AllName1Tokens = ja.SelectToken(@"..Name=""Name1"""); //Get all names that are having Name = "Name1" irrespective of branch
由于我没有类的二进制文件和Json字符串的结构是如此巨大,以至于很难使用动态.因此,在反序列化后无法在对象上使用LINQ.我不想将Json字符串转换为XML或其他格式来进行选择.另外我不想编写代码来解析它.
SelectToken函数的Path参数的语法是什么?如何选择Name =“Name1”的所有员工EmpId?
Edit1:如果SelectToken无法做到这一点,是否可以使用Jbject字符串(而不是真实对象)上的JObject.Select(LINQ查询)获取结果?正则表达式怎么样?
解决方法
来自JSON.NET的作者:
由于Json.NET 6.0完全支持JSONPath,因此使用了一个类似于JSON查询语言的XPath.
JObject o = JObject.Parse(@"{ ""Manufacturers"": [ { ""Name"": ""Acme Co"",""Products"": [ { ""Name"": ""Anvil"",""Price"": 50 } ] },{ ""Name"": ""Contoso"",""Products"": [ { ""Name"": ""Elbow Grease"",""Price"": 99.95 },{ ""Name"": ""Headlight Fluid"",""Price"": 4 } ] } ] }"); // manufacturer with the name 'Acme Co' var acme = o.SelectToken("$.Manufacturers[?(@.Name == 'Acme Co')]");
关于blog post的更多细节