尝试从URL反序列化.NET的JSON,但收到错误

时间:2014-03-01 12:34:14

标签: c# json

我正在尝试使用以下代码反序列化网址:

     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.

网址为:http://www.classicube.net/api/serverlist/

4 个答案:

答案 0 :(得分:5)

这是一个json数组。使用

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

答案 1 :(得分: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);

答案 2 :(得分:0)

您必须使用List<RootObject>对其进行正确反序列化:

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

答案 3 :(得分:-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; }

}