简体   繁体   中英

JSON Deserialization Exception

I made a code to parse this JSON

I've generated the class with 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; }
}

I perform the request on this way:

 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);
    }
}

the compiler return me:

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

on the obj deserialization.

How can I fix it? How can i choose the correct deserialization?

You're trying to deserialize it into a list of RootObject but in reality the JSON is just a single root object.

Try

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

instead. And then of course you need to change your for loop because obj is no longer a List<> . If you want to iterate through the teams, then:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM