JSON反序列化异常

时间:2015-06-16 15:09:42

标签: c# json wpf

我制作了一个代码来解析这个JSON

我用JSON2C#:

生成了这个类
public class Link
{
    public string self { get; set; }
    public string soccerseason { get; set; }
}

public class Self
{
    public string href { get; set; }
}

public class Fixtures
{
    public string href { get; set; }
}

public class Players
{
    public string href { get; set; }
}

public class Links
{
    public Self self { get; set; }
    public Fixtures fixtures { get; set; }
    public Players players { get; set; }
}

public class Team
{
    public Links _links { get; set; }
    public string name { get; set; }
    public string code { get; set; }
    public string shortName { get; set; }
    public string squadMarketValue { get; set; }
    public string crestUrl { get; set; }
}

public class RootObject
{
    public List<Link> _links { get; set; }
    public int count { get; set; }
    public List<Team> teams { get; set; }
}

我以这种方式执行请求:

 private void League_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    string requestUrl = "http://api.football-data.org/alpha/soccerseasons/122/teams";
    HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
    request.Method = "GET";
    request.ContentType = "application/json";
    string responseText;
    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    using (var responseStream = new StreamReader(response.GetResponseStream()))
    {
        responseText = responseStream.ReadToEnd();
    }

    List<RootObject> obj = JsonConvert.DeserializeObject<List<RootObject>>(responseText);

    foreach (var item in obj)
    {
        Home.Items.Add(item.name);
    }
}

编译器返回我:

 Unhandled Exception "Newtonsoft.Json.JsonSerializationException" in Newtonsoft.Json.dll
Cannot deserialize the current JSON object (e.g {"name":"value"}) into type "System.Collections.Generic.List"1
[Test.MainWindow+RootObject]" because the type requires a Json array (e.g. [1,2,3]) to deserialize correctly.

关于obj反序列化。

我该如何解决?我如何选择正确的反序列化?

1 个答案:

答案 0 :(得分:2)

您尝试将其反序列化为RootObject列表,但实际上JSON只是一个根对象。

尝试

RootObject obj = JsonConvert.DeserializeObject<RootObject>(responseText);

代替。当然,您需要更改for循环,因为obj不再是List<>。如果你想遍历团队,那么:

foreach (var item in obj.teams)
{
    Home.Items.Add(item.name);
}