如何从指定级别获取json节点?

时间:2016-12-08 15:35:02

标签: c# json json.net jsonpath

我有这个json:

 {  
   "treeview":[  
      {  
         "text":"blah",
         "nodes":[  

         ]
      },
      {  
         "text":"blah",
         "nodes":[  

         ]
      },
      {  
         "text":"blah",
         "nodes":[  
            {  
               "text":"blah",
               "nodes":[  
                  {  
                     "text":"foo",
                     "nodes":[  
                         // I need to put data in here !!!
                     ]
                  }
               ]
            }
         ]
      },
      {  
         "text":"blah",
         "nodes":[  

         ]
      },
      {  
         "text":"foo",
         "nodes":[  
             // Not here !
         ]
      }
   ]
}

我需要把值放在“nodes”元素上,其中我在第2级“text”等于“foo”。

这是我到目前为止所尝试的内容:

var json = myJson;
// First approach
var selector = (JArray)json.SelectTokens($"$..treeview[?(@.text == 'foo')]");
// Second approach
var selector2 = (JArray)json.SelectToken($"$.treeview[?(@...text == 'foo')]");

selector.Add(new JObject(new JProperty("text", "myValue"));

我不明白查询中的“点”是如何工作的......我只知道当你输入2“点”时它会浏览整个JSON ...有没有办法只查询一个特定的缩进级别?

3 个答案:

答案 0 :(得分:5)

我想通了,是的,当我们想在text plain中查询json时,我们可以指定一个级别缩进,这是如何:

var json = myJson;
var selector = (JArray)json.SelectTokens($"$.treeview[*].nodes[*].nodes[(@.text =='foo')].nodes");
selector.Add(new JObject(new JProperty("text", "myValue")));

您可以在此处测试: http://jsonpath.com/

复制json部分中的json示例并将其添加到jsonPath中:$.treeview[*].nodes[*].nodes[*].text

如果没有在数组中指定任何索引,您可以在所需'foo'中获取"level of identation"值,只需使用此'*'代替int

答案 1 :(得分:1)

使用对象比简单的json文本更容易...

使用Newtonsoft.Json包...

class Program
{
    static void Main(string[] args)
    {
        var jsonstring = "{\"text\":\"blah\",\"nodes\":[{\"text\":\"foo\", \"nodes\": []}, {\"text\":\"bar\", \"nodes\": []}, {\"text\":\"foo\", \"nodes\": []}]}";

        //This is the root node
        var firstLevelNodes = JsonConvert.DeserializeObject<Node>(jsonstring);

        //All the nodes in the root nodes node collection
        var secondLevelNodes = firstLevelNodes.nodes;

        //All of the nodes in the collections of the second level nodes
        var thirdLevelNodes = secondLevelNodes.SelectMany(sln => sln.nodes);


        Console.WriteLine("First Level Nodes: \n" + JsonConvert.SerializeObject(firstLevelNodes).PrettyPrint());
        Console.WriteLine();
        Console.WriteLine("Second Level Nodes: \n" + JsonConvert.SerializeObject(secondLevelNodes).PrettyPrint());
        Console.WriteLine();
        Console.WriteLine("Third Level Nodes: \n" + JsonConvert.SerializeObject(thirdLevelNodes).PrettyPrint());

        secondLevelNodes.First().nodes = new List<Node> { new Node { text = "new node" , nodes = new List<Node>() } };

        Console.WriteLine();
        Console.WriteLine("Third Level Nodes (with new node): \n" + JsonConvert.SerializeObject(thirdLevelNodes).PrettyPrint());

        Console.ReadLine();
    }
}

public static class JSONExtensions
{
    public static string PrettyPrint(this string json)
    {
        dynamic parsedJson = JsonConvert.DeserializeObject(json);
        return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
    }

}


[Serializable]
public class Node
{
    public string text { get; set; }
    public IEnumerable<Node> nodes { get; set; }
}

输出:

First Level Nodes:
{
  "text": "blah",
  "nodes": [
    {
      "text": "foo",
      "nodes": []
    },
    {
      "text": "bar",
      "nodes": []
    },
    {
      "text": "foo",
      "nodes": []
    }
  ]
}

Second Level Nodes:
[
  {
    "text": "foo",
    "nodes": []
  },
  {
    "text": "bar",
    "nodes": []
  },
  {
    "text": "foo",
    "nodes": []
  }
]

Third Level Nodes:
[]

Third Level Nodes (with new node):
[
  {
    "text": "new node",
    "nodes": []
  }
]

编辑:

因此,如果您只想要使用文本foo的第二级节点,请使用..

var secondLevelFooNodes = secondLevelNodes.Where(sln=>sln.text == "foo");
//then use these nodes

EDIT2:

使用您的实际JSON对象也需要TreeView类......

class Program
{
    static void Main(string[] args)
    {
        var jsonstring = "{\"treeview\":[{\"text\":\"blah\",\"nodes\":[]},{\"text\":\"blah\",\"nodes\":[]},{\"text\":\"blah\",\"nodes\":[{\"text\":\"blah\",\"nodes\":[{\"text\":\"foo\",\"nodes\":[]}]}]},{\"text\":\"blah\",\"nodes\":[]},{\"text\":\"foo\",\"nodes\":[]}]}";

        //This is the root node
        var treeView = JsonConvert.DeserializeObject<TreeView>(jsonstring);

        //All the nodes in the root nodes node collection
        var firstLevelNodes = treeView.treeview;

        //All of the nodes in the collections of the first level nodes
        var secondLevelNodes = firstLevelNodes.SelectMany(fln => fln.nodes);

        //All of the nodes in the collections of the second level nodes
        var thirdLevelNodes = secondLevelNodes.SelectMany(sln => sln.nodes);

        Console.WriteLine("The TreeView: \n" + JsonConvert.SerializeObject(treeView, Formatting.Indented));

        thirdLevelNodes.First(sln => sln.text == "foo").nodes = new List<Node> { new Node { text = "new node", nodes = new List<Node>() } };

        Console.WriteLine();
        Console.WriteLine("The TreeView (with new node): \n" + JsonConvert.SerializeObject(treeView, Formatting.Indented));

        Console.ReadLine();
    }
}

[Serializable]
public class Node
{
    public string text { get; set; }
    public IEnumerable<Node> nodes { get; set; }
}

[Serializable]
public class TreeView
{
    public IEnumerable<Node> treeview { get; set; }
}

输出:

The TreeView:
{
  "treeview": [
    {
      "text": "blah",
      "nodes": []
    },
    {
      "text": "blah",
      "nodes": []
    },
    {
      "text": "blah",
      "nodes": [
        {
          "text": "blah",
          "nodes": [
            {
              "text": "foo",
              "nodes": []
            }
          ]
        }
      ]
    },
    {
      "text": "blah",
      "nodes": []
    },
    {
      "text": "foo",
      "nodes": []
    }
  ]
}

The TreeView (with new node):
{
  "treeview": [
    {
      "text": "blah",
      "nodes": []
    },
    {
      "text": "blah",
      "nodes": []
    },
    {
      "text": "blah",
      "nodes": [
        {
          "text": "blah",
          "nodes": [
            {
              "text": "foo",
              "nodes": [
                {
                  "text": "new node",
                  "nodes": []
                }
              ]
            }
          ]
        }
      ]
    },
    {
      "text": "blah",
      "nodes": []
    },
    {
      "text": "foo",
      "nodes": []
    }
  ]
}

答案 2 :(得分:1)

您需要指定“nodes”数组的正确路径。试试这个:

JObject json = JObject.Parse("{\"treeview\":[{\"text\":\"blah\",\"nodes\":[]},{\"text\":\"blah\",\"nodes\":[]},{\"text\":\"blah\",\"nodes\":[{\"text\":\"blah\",\"nodes\":[{\"text\":\"foo\",\"nodes\":[]}]}]},{\"text\":\"blah\",\"nodes\":[]},{\"text\":\"foo\",\"nodes\":[]}]}");
JArray array = (JArray)json.SelectToken("treeview[2].nodes[0].nodes[0].nodes");
array.Add(new JObject(new JProperty("text", "myValue")));