2016-06-25 48 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. 獲取的成績單部(S) JSON響應。
  2. 處理這些字符串。

    • 我對此很陌生。轉換爲字符串只能稱爲序列化。爲什麼反序列化會在這裏起作用?

轉換爲字符串:我做到了使用:

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


      responseFromServer = reader.ReadToEnd(); 

如何實現這一目標?

+0

有沒有需要反序列化 - 但它會讓你的生活更輕鬆:o) –

+0

反序列化JSON將它轉換回.NET對象。然後,您可以訪問該對象的屬性,而不是進行一堆字符串解析。使用像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); 
    } 
} 

但你可能要做出明確的類它來代替。那麼你可以這樣做:

MyRootObject root = JsonConvert.DeserializeObject<MyRootObject>(responseFromServer); 

並處理它像任何其他的.NET對象。

+2

使用剪貼板中的JSON VS提供菜單編輯/粘貼特殊/粘貼JSON作爲類 –

3

您可以將JSON解析爲具體的類並在之後使用。

爲此,您可以使用像json2csharp這樣的服務,它根據您提供的JSON生成類。或者,您可以使用Visual Studio內置功能粘貼JSON如類

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.NET到字符串化JSON解析到具體的類實例:

var root = JsonConvert.DeserializeObject<RootObject>(responseFromServer);