Search code examples
c#jsonjson.netriot-games-api

JSON.Net Deserialization of non-generic Root Objects


I'm currently working on a project where I make a request to the Riot Games API, parse the JSON, and do some stuff with it. I have the request working, and I know I'm getting valid JSON. My issue is using JSON.Net to deserialize the JSON.

The JSON is of the following structure:

{
  "xarcies": {
        "id": 31933985,
        "name": "Farces",
        "profileIconId": 588,
        "revisionDate": 1450249383000,
        "summonerLevel": 30
    }
}

I want to load this data into the following class

[JsonObject(MemberSerialization.OptIn)]
class Summoner
{
    [JsonProperty("id")]
    public long id {get;set;}

    [JsonProperty("name")]
    public string name { get; set; }

    [JsonProperty("profileIconId")]
    public int profileIconId { get; set; }

    [JsonProperty("revisionDate")]
    public long revisionDate { get; set; }

    [JsonProperty("summonerLevel")]
    public long summonerLevel { get; set; }
}

The issue I'm having is that because I'm given a "xarcies" object that contains the information I need, I'm not sure how to go about designing a class that can accept the JSON data. I've seen some examples that use a RootObject class to take the object and that class has a subclass that all the pairs are put into, but I can't seem to get it to work. Every time I run it the attributes for the object end up being NULL.


Solution

  • You can deserialize your JSON as a Dictionary<string, Summoner>:

    var root = JsonConvert.DeserializeObject<Dictionary<string, Summoner>>(jsonString);
    

    The dictionary will be keyed by the user name, in this case "xarcies". See Deserialize a Dictionary.