2016-06-25 3 views
0

api에 쿼리를 작성한 후 json 응답을받습니다.C#에서 JSON 응답 구문 분석

내가 위에서 JSON 결과에 두 가지 일을 할 필요가
{ 
    "results": [ 
     { 
     "alternatives": [ 
      { 
       "confidence": 0.965, 
       "transcript": "how do I raise the self esteem of a child in his academic achievement at the same time " 
      } 
     ], 
     "final": true 
     }, 
     { 
     "alternatives": [ 
      { 
       "confidence": 0.919, 
       "transcript": "it's not me out of ten years of pseudo teaching and helped me realize " 
      } 
     ], 
     "final": true 
     }, 
     { 
     "alternatives": [ 
      { 
       "confidence": 0.687, 
       "transcript": "is so powerful that it can turn bad morals the good you can turn awful practice and the powerful once they can teams men and transform them into angel " 
      } 
     ], 
     "final": true 
     }, 
     { 
     "alternatives": [ 
      { 
       "confidence": 0.278, 
       "transcript": "you know if not on purpose Arteaga Williams who got in my mother " 
      } 
     ], 
     "final": true 
     }, 
     { 
     "alternatives": [ 
      { 
       "confidence": 0.621, 
       "transcript": "for what pink you very much " 
      } 
     ], 
     "final": true 
     } 
    ], 
    "result_index": 0 
} 

(나는 문자열 *로 유지) :

json으로 같은 것입니다

  1. 성적 증명서 부분 (들)를 가져옵니다 json 응답.
  2. 해당 문자열을 처리하십시오.

    • 새로운 소식입니다. 문자열로 변환하는 것은 직렬화라고 불립니다. 왜 deserialization이 도움이 될까요?

문자열로 변환 :

var reader = new StreamReader(response.GetResponseStream()); 


      responseFromServer = reader.ReadToEnd(); 

어떻게 이것을 달성하기 위해 : 내가 사용을 했습니까?

+0

역 직렬화의 필요는 없습니다. 그러나 당신의 삶을 편하게 만듭니다. o) –

+0

JSON을 역 직렬화하면 .NET 객체로 역 직렬화됩니다. 그런 다음 문자열 구문 분석을 수행하는 대신 해당 객체의 속성에 액세스 할 수 있습니다. deserialization을 돕기 위해 Newtonsoft JSON.NET과 같은 라이브러리를 사용하십시오. – wablab

답변

1

역 직렬화해야합니다. 그것은 그것을 다루는 가장 쉬운 방법입니다. Json.NETdynamic 사용하여 그과 같습니다

dynamic jsonObj = JsonConvert.DeserializeObject(responseFromServer); 
foreach (var result in jsonObj.results) { 
    foreach (var alternative in result.alternatives) { 
     Console.WriteLine(alternative.transcript); 
    } 
} 

하지만 대신에 그것을 명시 적으로 수업을 할 수 있습니다. 그럼 당신은 할 수있다 :

그리고 그 밖의 다른 .NET 객체처럼 처리한다.

+2

클립 보드에 JSON이있는 경우 VS 메뉴 제공 편집/붙여 넣기 특수/JSON을 클래스로 붙여 넣기 –

3

JSON을 구체적인 클래스로 구문 분석하고 이후에 작업 할 수 있습니다.

이렇게하려면 제공된 JSON을 기반으로 클래스를 생성하는 json2csharp과 같은 서비스를 사용할 수 있습니다.

enter image description here

public class Alternative 
{ 
    public double confidence { get; set; } 
    public string transcript { get; set; } 
} 

public class Result 
{ 
    public List<Alternative> alternatives { get; set; } 
    public bool final { get; set; } 
} 

public class RootObject 
{ 
    public List<Result> results { get; set; } 
    public int result_index { get; set; } 
} 

그런 다음 구체적인 클래스 인스턴스에 캐릭터 라인 JSON을 구문 분석 JSON.NET를 사용할 수 있습니다 :

var root = JsonConvert.DeserializeObject<RootObject>(responseFromServer); 
양자 택일로, 당신은 클래스으로 내장 된 기능 붙여 넣기 JSON은 Visual Studio를 사용할 수 있습니다