2016-10-20 4 views
0

동적으로 생성되고 명확한 구조가없는 JSON 파일을 구문 분석하고 싶습니다.C#에서 jstree 용으로 생성 된 json 파일을 구문 분석합니다.

[ 
    { 
    "children": [ 
     { 
     "children": [ 
      { 
      "children": [], 
      "text": "Child node 2.txt", 
      "isFolder": false, 
      "id": "1childnode2.txt", 
      "itsPath": "C:\\Users\\pandyapa\\Root node\\Child node 2.txt", 
      "type": "itsfile" 
      } 
     ], 
     "text": "Child node 1.txt", 
     "isFolder": false, 
     "id": "0childnode1.txt", 
     "itsPath": "C:\\Users\\pandyapa\\Root node\\Child node 1.txt", 
     "type": "itsfile" 
     }, 
     { 
     "children": [], 
     "text": "Child node 2.txt", 
     "isFolder": false, 
     "id": "1childnode2.txt", 
     "itsPath": "C:\\Users\\pandyapa\\Root node\\Child node 2.txt", 
     "type": "itsfile" 
     }, 
     { 
     "children": [], 
     "text": "Child node 3.txt", 
     "isFolder": false, 
     "id": "2childnode3.txt", 
     "itsPath": "C:\\Users\\pandyapa\\Root node\\Child node 3.txt", 
     "type": "itsfile" 
     } 
    ], 
    "text": "Root node", 
    "isFolder": true, 
    "id": "3rootnode", 
    "itsPath": "C:\\Users\\pandyapa\\Root node", 
    "type": "default" 
    } 
] 

이 JSON에는 중첩 된 하위 항목이있을 수 있습니다. 각 JSON 객체를 구문 분석하고 "id"키를 비교하여 "itspath"값을 검색하려고합니다. 시도했지만 실패했습니다. 어떤 도움을 주셔서 감사합니다. 그것은 당신의 JSON처럼 나에게 보이는

+2

읽기 [질문] 당신의 시도를 보여주고 그들이 어떻게 실패

var idToFind = "2childnode3.txt"; var node = nodes.SelectMany(n => n.DescendantsAndSelf()) .Where(n => n.Id == idToFind) .FirstOrDefault(); if (node != null) { Console.WriteLine(node.ItsPath); } else { Console.WriteLine("Not found"); } 

바이올린을 :

public IEnumerable<Node> DescendantsAndSelf() { yield return this; if (Children != null) { foreach (Node child in Children) { yield return child; } } } 

지금 당신은 ID에 의해 특정 노드를 찾기 위해이 작업을 수행 할 수 있습니다. – CodeCaster

+2

시도해주세요, @Parth : http://stackoverflow.com/questions/17038810/newtonsoft-json-deserialize – Alexandru

답변

0

이 재귀 클래스에 의해 표현 될 수있는 매우 명확한 구조를 가지고있다 :

public class Node 
{ 
    public Node[] Children { get; set; } 
    public string Text { get; set; } 
    public bool IsFolder { get; set; } 
    public string Id { get; set; } 
    public string ItsPath { get; set; } 
    public string Type { get; set; } 
} 

는 그것은 JSON은 중첩 될 수 있음을 수 있습니다 그리고 당신은하지 않을 수 있습니다 각 레벨에 얼마나 많은 레벨이나 얼마나 많은 아이들이 있을지 미리 알지만 사실은 각 "노드"가 균일 한 구조를 유지한다는 것입니다. Json.Net과 같은 구문 분석기를 사용하여 쉽게 deserialize 할 수 있기 때문에이 방법이 유용합니다. 사실, 당신은 한 줄의 코드를 수행 할 수 있습니다 당신이 직렬화 노드가 있으면

List<Node> nodes = JsonConvert.DeserializeObject<List<Node>>(json); 

, 당신은 당신이 원하는 하나를 찾을 수 있어야합니다. 짧은 "DescendantsAndSelf"메서드를 클래스에 도입하면 LINQ 메서드를 사용하여 쿼리를 쿼리 할 수있게 만들 수 있습니다. , https://dotnetfiddle.net/u9gDTc