2014-03-01 183 views
1

我嘗試使用下面的代碼反序列化網址:試圖Deserialise JSON用於.NET從URL,但得到一個錯誤

 private void RefeshList_Click(object sender, EventArgs e) 
     { 
      WebClient list = new WebClient(); 
      string text = list.DownloadString("http://www.classicube.net/api/serverlist/"); 
      var server = JsonConvert.DeserializeObject<RootObject>(text); 
      serverlist.Text = text; 

      } 
     } 
    } 

public class RootObject 
{ 
    public string hash { get; set; } 
    public string ip { get; set; } 
    public int maxplayers { get; set; } 
    public string mppass { get; set; } 
    public string name { get; set; } 
    public int players { get; set; } 
    public int port { get; set; } 
    public int uptime { get; set; } 

} 

但我得到一個錯誤:

An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll 

Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'RootObject' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. 

To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. 

Path '', line 1, position 1. 

的URL是:http://www.classicube.net/api/serverlist/

+0

錯誤消息告訴您問題是 - 什麼只是說:) – theMayer

回答

5

它是一個JSON數組。使用

var server = JsonConvert.DeserializeObject<List<RootObject>>(text); 
-2
"hash": "84ce710714eedcdfd7ef22d4776671b0" 
"maxplayers": 64 
"name": "All in the Mined" 
"players": 0 
"uptime": 2106398 

您需要設置這樣的

public class RootObject 
{ 
    public string hash { get; set; } 
    public int maxplayers { get; set; } 
    public string name { get; set; } 
    public int players { get; set; } 
    public int uptime { get; set; } 

} 
+1

這是沒有問題的。問題是從服務器返回的文本描述了一個集合,如[]所示。 – theMayer

1

類除了列出的正確答案,我想走得更遠了一步。如果您檢查從服務器返回的JSON響應,您將看到:

[ 
    {"hash": "84ce710714eedcdfd7ef22d4776671b0", "maxplayers": 64, "name": "All in the Mined", "players": 0, "uptime": 2107198}, 

[在開始的時候是指在JSON語法定義的數組。很多時候,人們可能會看到包含數組屬性的JSON對象;然而,這不是這種情況。這意味着你的代碼需要返回一個數組(並且大多數序列化器都理解數組是IEnumerables,所以他們對任何IEnumerable都很滿意)。

如果你考慮一下,那就很有道理。您可以看到JSON響應中列出的大約30個對象 - 您需要一個適當的數據結構來包含所有返回的對象。單個對象不匹配。

因此,您需要稍微更改代碼,方法是在其中添加List<>。這是這裏唯一需要的改變。

var server = JsonConvert.DeserializeObject<List<RootObject>>(text);

0

你必須使用List<RootObject>正確反序列化:

List<RootObject> server = JsonConvert.DeserializeObject<List<RootObject>>(text); 
+0

@WWasif Hossain你總是做同樣的事情。 http://stackoverflow.com/questions/22020684/get-text-in-string-between-text-in-said-string –

+0

@ L.B我想澄清你的困惑,它只是重疊的事件。當我看到尚未接受答案時,我試圖立即回答。我不知道是否無意中將答案與某人相匹配是否有錯。 –

+0

你認爲這是一個很好的態度?而不是發佈相同的答案,upvote正確的。 (我不是說幾分鐘的差異,我說*半小時以後*。) –

相關問題