2017-11-01 3 views
-3

JSON 응답 문자열에서 특정 부분을 가져 오려고합니다.JSON 응답 (응답에서 특정 부분 가져 오기)

{ 
    "metadata": { 
    "provider": "Oxford University Press" 
    }, 
    "results": [ 
    { 
     "id": "door", 
     "language": "en", 
     "lexicalEntries": [ 
     { 
      "entries": [ 
      { 
       "homographNumber": "000", 
       "senses": [ 
       { 
        "definitions": [ 
        "a hinged, sliding, or revolving barrier at the entrance to a building, room, or vehicle, or in the framework of a cupboard" 
        ], 
        "id": "m_en_gbus0290920.005", 
        "subsenses": [ 
        { 
         "definitions": [ 
         "a doorway" 
         ], 
         "id": "m_en_gbus0290920.008" 
        }, 
        { 
         "definitions": [ 
         "used to refer to the distance from one building in a row to another" 
         ], 
         "id": "m_en_gbus0290920.009" 
        } 
        ] 
       } 
       ] 
      } 
      ], 
      "language": "en", 
      "lexicalCategory": "Noun", 
      "text": "door" 
     } 
     ], 
     "type": "headword", 
     "word": "door" 
    } 
    ] 
} 

이 코드를

"정의"얻기 위해 노력하고 있어요 : A와 입구에 [ "경첩, 슬라이딩, 또는 회전 장벽을 여기

는 JSON 코드 건물, 방 또는 차량 또는 찬장 틀 "

문자열에 내 코드는 다음과 같습니다.

string language = "en"; 
      string word_id = textBox1.Text.ToLower(); 

      String url = "https://od-api.oxforddictionaries.com:443/api/v1/entries/" + language + "/" + word_id+"/definitions"; 

      HttpClient client = new HttpClient(); 

      client.BaseAddress = new Uri(url); 
      client.DefaultRequestHeaders.Add("app_id", app_Id); 
      client.DefaultRequestHeaders.Add("app_key", app_Key); 

      HttpResponseMessage response = client.GetAsync(url).Result; 
      if (response.IsSuccessStatusCode) 
      { 
       var result = response.Content.ReadAsStringAsync().Result; 
       var s = JsonConvert.DeserializeObject(result); 

       textBox2.Text = s.ToString(); 

      } 
      else MessageBox.Show(response.ToString()); 

저는 C#을 사용하고 있습니다.

+4

'나는 그것을 증명 .' C#을 사용하고있다 - 우리가 사용하는 코드를 보여이 실패하는 방법과 무슨 문제 야. [ask]를 읽고 [둘러보기] – Plutonix

+0

https://hastebin.com/ukeqemibiv.cs –

+1

시도한 것을 보여주기 위해 질문을 편집하십시오. 나는 당신의 질문을 전체적으로 보려고 3 개의 탭을 열 필요가 없다. –

답변

3

의 C# 클래스

1 단계는 우리가 C#에서 데이터를 표현 할 수 있도록 몇 가지 클래스를 만드는 것입니다. 당신이 그들을 가지고 있지 않다면 ... QuickType does that.

namespace QuickType 
{ 
    using System; 
    using System.Net; 
    using System.Collections.Generic; 

    using Newtonsoft.Json; 

    public partial class GettingStarted 
    { 
     [JsonProperty("metadata")] 
     public Metadata Metadata { get; set; } 

     [JsonProperty("results")] 
     public Result[] Results { get; set; } 
    } 

    public partial class Result 
    { 
     [JsonProperty("id")] 
     public string Id { get; set; } 

     [JsonProperty("language")] 
     public string Language { get; set; } 

     [JsonProperty("lexicalEntries")] 
     public LexicalEntry[] LexicalEntries { get; set; } 

     [JsonProperty("type")] 
     public string Type { get; set; } 

     [JsonProperty("word")] 
     public string Word { get; set; } 
    } 

    public partial class LexicalEntry 
    { 
     [JsonProperty("entries")] 
     public Entry[] Entries { get; set; } 

     [JsonProperty("language")] 
     public string Language { get; set; } 

     [JsonProperty("lexicalCategory")] 
     public string LexicalCategory { get; set; } 

     [JsonProperty("text")] 
     public string Text { get; set; } 
    } 

    public partial class Entry 
    { 
     [JsonProperty("homographNumber")] 
     public string HomographNumber { get; set; } 

     [JsonProperty("senses")] 
     public Sense[] Senses { get; set; } 
    } 

    public partial class Sense 
    { 
     [JsonProperty("definitions")] 
     public string[] Definitions { get; set; } 

     [JsonProperty("id")] 
     public string Id { get; set; } 

     [JsonProperty("subsenses")] 
     public Subsense[] Subsenses { get; set; } 
    } 

    public partial class Subsense 
    { 
     [JsonProperty("definitions")] 
     public string[] Definitions { get; set; } 

     [JsonProperty("id")] 
     public string Id { get; set; } 
    } 

    public partial class Metadata 
    { 
     [JsonProperty("provider")] 
     public string Provider { get; set; } 
    } 

    public partial class GettingStarted 
    { 
     public static GettingStarted FromJson(string json) => JsonConvert.DeserializeObject<GettingStarted>(json, Converter.Settings); 
    } 

    public static class Serialize 
    { 
     public static string ToJson(this GettingStarted self) => JsonConvert.SerializeObject(self, Converter.Settings); 
    } 

    public class Converter 
    { 
     public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings 
     { 
      MetadataPropertyHandling = MetadataPropertyHandling.Ignore, 
      DateParseHandling = DateParseHandling.None, 
     }; 
    } 
} 

역 직렬화

당신은 우리는 또한 직렬화하고 우리를 위해 생성 된 역 직렬화하는 컨버터를 가지고 있음을 알 수 있습니다. ...

var description = result.results.lexicalEntries.First() 
    .entries.First() 
    .senses.First() 
    .definitions.First(); 

First()의 모든 아래로 항목에 당신의 방법을 찾기 위해 result 변수 및 사용 점에서

var result = JsonConvert.DeserializeObject<GettingStarted>(json); 

사용

시작하십시오 직렬화 비트는 간단하다 호출은 데이터 배열의 각 부분으로 인해 발생합니다. 이를 위해서는 System.Linq을 참조해야합니다. 이러한 레벨 중 하나 이상 또는 미만인 경우 수행 할 작업을 약간 읽으려고합니다 (콜렉션을 사용하여 작업하거나 트래버스를 더 많이 수행해야 할 수도 있음).

0

구문 분석하려고하는 JSON의 이름을 속성으로 갖는 클래스를 생성 할 수 있습니다. 그렇게하면 JSON을 해당 클래스의 인스턴스로 deserialize하고 필요한 모든 속성을 가져올 수 있습니다. Newtonsoft.Json 패키지를 사용해야합니다.

예 클래스 :

public class YourClass 
{ 
    public string propertyA { get; set; } 
    public string propertyB { get; set; } 
} 

그리고 메인 코드 :

YourClass yourClass = new YourClass(); 
try 
{ 
    yourClass = JsonConvert.DeserializeObject<YourClass>(yourJsonStringGoesHere); 
} 
catch (Exception ex) 
{ 
     //log exception here 
} 
관련 문제