2016-09-20 2 views
1

아래에 언급 된 JSON을 구문 분석하고 screenshot.thumbnailUrl의 모든 값을 가져오고 싶습니다. 하지만 내 제약 조건은 다음과 같습니다.키를 모르는 상태에서 json을 읽으십시오. #

일부 노드에는 스크린 샷이 없습니다. 이 예제에서는 "날씨"와 "엔터티"만이 있습니다.

노드 이름을 모르겠습니다. 이 예제에서는 "weather"또는 "entities"라는 노드가 있다는 것을 알지 못했습니다. 이 노드는 json을 얻기 위해 만든 쿼리를 기반으로 자동 생성됩니다.

스크린 샷을 표시 할 수있는 장소는 두 곳입니다. (1) 루트 객체의 하위 예. weather.screenshot (2) 루트 객체의 모든 자식 값 (예 : entities.value [0] .screenshot, entities.value [1] .screenshot 등

{ "_type": "SearchResponse", "queryContext": {}, "webPages": {}, "entities": { 
    "queryScenario": "DominantEntity", 
    "value": [ 
     { 
     "_type": "Place", 
     "id": "https://www.someapi.com/api/v6/#Entities.0", 
     "screenshot": { 
      "thumbnailUrl": "http://Screenshot_URL_I_Want", 
      "width": 285 
     }, 
     "name": "Seattle", 
     "entityPresentationInfo": {}, 
     "bingId": "5fbba6b8-85e1-4d41-9444-d9055436e473", 
     "boundingBox": [], 
     "weather": {}, 
     "timeZone": "Pacific Standard Time" 
     } 
    ] }, "images": {}, "weather": { 
    "id": "https://www.someapi.com/api/v6/#Weather", 
    "screenshot": { 
     "thumbnailUrl": "http://Screenshot_URL_I_Want", 
     "width": 285 
    }, 
    "location": {}, 
    "currentWeather": {}, 
    "dailyForecast": [] }, "rankingResponse": {} } 
+0

당신은 역 직렬화를 사용할 수 있습니까? – StellaMaris

답변

2

당신은 JSON 파싱이 같은 코드를 사용하여 재귀 적으로 반복 할 수있다.

이것은 나를 위해 일한 것입니다
using Newtonsoft.Json.Linq; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace ConsoleApplication2 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string json = @"....your JSON ...."; 

      var node = JToken.Parse(json); 

      RecursiveDescent(node, n => 
      { 
       JToken url = n["thumbnailUrl"]; 
       if (url != null && url.Type == JTokenType.String) 
       { 
        var nodeWeWant = url?.Parent?.Parent?.Parent?.Parent; 

        Console.WriteLine(nodeWeWant.ToString()); 
       } 
      }); 
     } 

     static void RecursiveDescent(JToken node, Action<JObject> action) 
     { 
      if (node.Type == JTokenType.Object) 
      { 
       action((JObject)node); 
       foreach (JProperty child in node.Children<JProperty>()) 
        RecursiveDescent(child.Value, action); 
      } 
      else if (node.Type == JTokenType.Array) 
      { 
       foreach (JToken child in node.Children()) 
        RecursiveDescent(child, action); 
      } 
     } 
    } 
} 
+0

감사합니다! 이건 재미 있네. 나는 그것을 할 수있는 더 쉬운 방법이 있었으면 좋겠다. :) –

2

... 내가 청소기를 찾고 있어요 : JSON의 당신의 유형은 정확하고 견고하게 RecursiveDescent하는 당신은 아마 전화의 람다의 논리를 수정해야합니다 솔루션 비록 ...

static async void getJobject(string jsonstring) 
     { 
      JObject response = await JObject.Parse(jsonstring); 
      foreach (var node in response.Children()) 
      { 
       Console.WriteLine(node.Path); 
       string propertyPath = node.Path + ".screenshot.thumbnailUrl"; 
       var token = response.SelectToken(propertyPath); 

       if (token != null) 
       { 
        Console.WriteLine("Check this=> " + token.ToString()); //Prints screenshot URL from weather 
       } 
       else 
       { 
        propertyPath = node.Path + ".value"; 
        token = response.SelectToken(propertyPath); 
        if (token != null) 
        { 
         int count = token.Children().Count(); 
         for (int i = 0; i < count; i++) 
         { 
          propertyPath = node.Path + ".value" + "[" + i.ToString() + "]" + ".screenshot.thumbnailUrl"; 
          var mytoken = response.SelectToken(propertyPath); 
          if (mytoken != null) 
          { 
           Console.WriteLine("Check this=> " + mytoken.ToString()); //Prints screenshot URL from entities 
          } 
         } 


        } 
       } 

      } 
     } 
관련 문제