2016-12-02 48 views
2

我有以下幾點:反序列化JSON使用C#返回項

{"documents": 
    [{"keyPhrases": 
     [ 
      "search results","Azure Search","fast search indexing","sophisticated search   capabilities","Build  great search experiences","time-sensitive search   scenarios","service availability","managed  service","service    updates","index corruption","near-instantaneous responses","multiple     languages","integrated Microsoft natural language stack","multiple   indexes","application  changes","ranking models","great relevance","years of   development","primary interaction  pattern","storage","Bing","data    volume","rich","suggestions","hassle of  dealing","Reliable     throughput","website","incremental cost","complexity","faceting","traffic","mobile     apps","business goals","users","applications","user expectations","Office" 
     ], 
    "id":"1"}], 
    "errors":[] 
} 

我需要提取的關鍵字句內的項目,但完全不知道該怎麼做。

我曾嘗試以下:

KeyPhraseResult keyPhraseResult = new KeyPhraseResult(); 

/// <summary> 
/// Class to hold result of Key Phrases call 
/// </summary> 
public class KeyPhraseResult 
{ 
    public List<string> keyPhrases { get; set; } 
} 

keyPhraseResult = JsonConvert.DeserializeObject<KeyPhraseResult>(content); 

content包含上面的JSON字符串。

但是,keyPhraseResult返回空值。

任何機構能幫助我走向正確的方向嗎?

謝謝。

+0

一個錯字,如果我沒有記錯。您的JSON中的'keyPhrases'和您的代碼中的'KeyPhrases' – RandomStranger

+1

「documents」是一組具有屬性「keyPhrases」的對象。您缺少數組級別和「文檔」屬性。 –

+0

感謝Bas,你是對的。我實際上並不知道他們需要完全相同(即使它實際上是合乎邏輯的)。我改變了它。 – AxleWack

回答

4
public class Document 
{ 
    public List<string> keyPhrases { get; set; } 
    public string id { get; set; } 
} 

public class RootObject 
{ 
    public List<Document> documents { get; set; } 
    public List<object> errors { get; set; } 
} 

你應該有這樣的結構:

var result = JsonConvert.DeserializeObject<RootObject>(content); 
+0

謝謝!這工作完美!然後,我添加了以下內容來使用KeyPhrases填充我的KeyPhraseResult類:keyPhraseResult.KeyPhrases = result.documents [0] .keyPhrases; - 再次感謝!! – AxleWack