将Json反序列化为C#类

9

我想使用RIOT API来制作适用于UWP的League of Legends应用。

当我访问他们的网站以生成JSON时,我会得到类似于以下内容:

{"gigaxel": {
  "id": 36588106,
   "name": "Gigaxel",
   "profileIconId": 713,
   "revisionDate": 1451577643000,
   "summonerLevel": 30
}}

当我使用Visual Studio 2015中的特殊粘贴方法将此JSON选择并复制到一个新类中时,我会得到具有以下属性的这些类:
public class Rootobject
{
    public Gigaxel gigaxel { get; set; }
}

public class Gigaxel
{
    public int id { get; set; }
    public string name { get; set; }
    public int profileIconId { get; set; }
    public long revisionDate { get; set; }
    public int summonerLevel { get; set; }
}

我创建了一个名为LOLFacade的新类,用于连接RiotAPI:
 public class LOLFacade
{
    private const string APIKey = "secret :D";

    public async static Task<Rootobject> ConnectToRiot(string user,string regionName)
    {
        var http = new HttpClient();
        string riotURL = String.Format("https://{0}.api.pvp.net/api/lol/{0}/v1.4/summoner/by-name/{1}?api_key={2}",regionName, user, APIKey);
        var response = await http.GetAsync(riotURL);

        var result = await response.Content.ReadAsStringAsync();

        return JsonConvert.DeserializeObject<Rootobject>(result);

    }

}

这是按钮事件处理程序方法:
        Rootobject root = new Rootobject { gigaxel = new Gigaxel() };
        root = await LOLFacade.ConnectToRiot("gigaxel","EUNE");
        string name = root.gigaxel.name;
        int level = root.gigaxel.summonerLevel;

        InfoTextBlock.Text = name + " is level " + level;

为了测试目的,我将regionName和用户硬编码。这适用于我的用户名:“gigaxel”。
当我尝试使用另一个用户名,例如“xenon94”时,我会收到一个异常:

Object reference not set to an instance of an object.

当我将Rootobject中的属性名称从gigaxel改为xenon94时,格式如下:
public class Rootobject
{
    public Gigaxel xenon94 { get; set; }
}

当我重新编译我的代码时,它可以适用于用户名xenon94,但对于我的用户名"gigaxel"却不能正常工作。
我希望它可以适用于任何给定的用户名。


看一下Newtonsoft的JObject。它们允许您将JSON解析为动态对象,您可以操纵并获取您关心的部分,请参见https://dev59.com/umgu5IYBdhLWcg3w0qRK。 - monkeyhouse
1个回答

7
问题在于json对象有一个被命名为gigaxel的属性。您需要检索内部对象,如下所示:
var json = JsonConvert.DeserializeObject<JObject>(x).First.First;

通过索引器,您可以获取名称和其他信息:

string name = (string)json["name"];
int summonerlevel = (int)json["summonerLevel"]

更详细地说,JsonConvert.DeserializeObject(x)会返回一个新的JObject对象,它只有一个对象。因此需要进行First调用。此外,该对象只有一个属性,名为"gigaxel"。这个属性的值就是我们需要的信息,例如名称。我们想无论属性的名称如何都能检索到此信息。因此,我们再次调用First以检索此属性的值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接