所以我是一名自学成才的C#程序员。我所知道的关于C#的一切都来自于在学校学习Java并将其应用于C#。我对类的了解不是很好,使用JSON数据几乎完全没有。所以我有这个JSON数据,我从HttpWebClient下拉,然后使用JSON.NET反序列化它。我使用json2csharp类生成器作为类结构。但是,我相信,我错过了一个步骤,导致对象只为所有内容都为null。
示例JSON数据 https://github.com/justintv/Twitch-API/blob/master/v3_resources/games.md获取/游戏/热门示例数据
我的代码
var client = new HttpClient();
var url = new Uri("https://api.twitch.tv/kraken/games/top");
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/vnd.twitchtv.v3+json"));
var response = await client.GetAsync(url);
var content = await response.Content.ReadAsStringAsync();
TwitchReturn objectHolder = JsonConvert.DeserializeObject<TwitchReturn>(content);
Console.WriteLine(objectHolder);
^这应该有objectHolder.top [0] .game.name;我只是不知道如何访问它。
Twitch Return Class
class TwitchReturn
{
public class Links
{
public string self { get; set; }
public string next { get; set; }
}
public class Box
{
public string large { get; set; }
public string medium { get; set; }
public string small { get; set; }
public string template { get; set; }
}
public class Logo
{
public string large { get; set; }
public string medium { get; set; }
public string small { get; set; }
public string template { get; set; }
}
public class Links2
{
}
public class Game
{
public string name { get; set; }
public int _id { get; set; }
public int giantbomb_id { get; set; }
public Box box { get; set; }
public Logo logo { get; set; }
public Links2 _links { get; set; }
}
public class Top
{
public int viewers { get; set; }
public int channels { get; set; }
public Game game { get; set; }
}
public class RootObject
{
public int _total { get; set; }
public Links _links { get; set; }
public List<Top> top { get; set; }
}
}
我确信我所犯的错误来自该课程和控制台声明,我只是不知道这样做。虽然我知道这很可能非常简单。
答案 0 :(得分:0)
只有当.Net Entity与传入的JSON数据明确匹配时,才能实现JSON到.NET对象的反序列化。在这里,您不必创建嵌套类,而是必须创建TwitchReturn类,并根据数据决定属性以及是否将是集合。
class TwitchReturn
{
public Links _links { get; set; }
public IEnumerable<Top> top { get; set; }
public RootObject rootObject { get; set; }
}
public class Links
{
public string self { get; set; }
public string next { get; set; }
}
public class Box
{
public string large { get; set; }
public string medium { get; set; }
public string small { get; set; }
public string template { get; set; }
}
public class Logo
{
public string large { get; set; }
public string medium { get; set; }
public string small { get; set; }
public string template { get; set; }
}
public class Links2
{
}
public class Game
{
public string name { get; set; }
public int _id { get; set; }
public int giantbomb_id { get; set; }
public Box box { get; set; }
public Logo logo { get; set; }
public Links2 _links { get; set; }
}
public class Top
{
public int viewers { get; set; }
public int channels { get; set; }
public Game game { get; set; }
}
public class RootObject
{
public int _total { get; set; }
public Links _links { get; set; }
public List<Top> top { get; set; }
}