[英]JSON Deserialization Exception
I made a code to parse this JSON 我编写了代码来解析此JSON
I've generated the class with JSON2C#: 我已经使用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. 关于obj反序列化。
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. 您尝试将其反序列化为
RootObject
列表,但实际上JSON只是单个根对象。
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<>
. 然后当然,您需要更改for循环,因为
obj
不再是List<>
。 If you want to iterate through the teams, then: 如果要遍历各个团队,则:
foreach (var item in obj.teams)
{
Home.Items.Add(item.name);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.