Deserialize JSON from Riot API C#

时光毁灭记忆、已成空白 提交于 2019-12-24 15:46:06

问题


I have some problem to deserialize JSON response from the RIOT API in C#. I want to get the list of "Champion" and the API return a stream like this :

{  
   "type":"champion",
   "version":"6.1.1",
   "data":{  
      "Thresh":{  
         "id":412,
         "key":"Thresh",
         "name":"Thresh",
         "title":"the Chain Warden"
      },
      "Aatrox":{  
         "id":266,
         "key":"Aatrox",
         "name":"Aatrox",
         "title":"the Darkin Blade"
      },...
    }
}

All data has the same attributes (id, key, name and title) so I create a champion class :

public class Champion
    {
        public int id { get; set; }
        public string key { get; set; }
        public string name { get; set; }
        public string title { get; set; }
    }

I need your help because i dont know how to deserialize this data... I need to create a Root class with type, version and data attributes (data is a list of champion)? I watched for used NewtonSoft Json but I dont found example who helped me.


回答1:


You can use the following root object (more accurately Data Transfer Object) to retrieve the champions from the API. This will return all champions without having to create a class for each champion.

public class RootChampionDTO
{
    public string Type { get; set; }
    public string Version { get; set; }
    public Dictionary<string, Champion> Data { get; set; }
}

then using Newtsonsoft's Json.NET, you would deserialize using the following:

JsonConvert.DeserializeObject<RootChampionDTO>(string json);



回答2:


If you want to use NewtonSoft:

JsonConvert.DeserializeObject<RootObject>(string json);

Json .NET Documentation: http://www.newtonsoft.com/json/help/html/SerializingJSON.htm




回答3:


Consider such classes:

public class ResponseModel
{
    public string Type { get; set; }

    public string Version { get; set; }

    public Dictionary<string, Champion> Data { get; set; }
}

public class Champion
{
    public int Id { get; set; }

    public string Key { get; set; }

    public string Name { get; set; }

    public string Title { get; set; }
}

And after use Newtonsoft.Json nuget package to deserialize your json:

 using Newtonsoft.Json;

 var result = JsonConvert.DeserializeObject<ResponseModel>(json);

Note that Newtonsoft.Json default settings allow you to correctly parse camelCase properties from json into PascalCase properties in C# classes.



来源:https://stackoverflow.com/questions/34921157/deserialize-json-from-riot-api-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!