Skip to main content
 首页 » 编程设计

c#之尝试从 URL 反序列化 .NET 的 JSON,但出现错误

2024年02月13日17jiqing9006

我正在尝试使用以下代码反序列化 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. 

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

请您参考如下方法:

这是一个json数组。使用

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