Search code examples
c#jsonapiasp.net-corejson-deserialization

How to JSON deserialize child objects ASP.NET Core


I'm trying to deserialize a JSON API response but not sure how I can access properties of a child object.

This is an example of the API response I am working with:

{
    "token_type": "Bearer",
    "expires_at": 1598830199,
    "expires_in": 21408,
    "refresh_token": "*Removed*",
    "access_token": "*Removed*",
    "athlete": {
        "id": *Removed*,
        "username": null,
        "resource_state": 2,
        "firstname": "Jon",
        "lastname": "Clyde",
        "city": "*Removed*",
        "state": "England",
        "country": "United Kingdom",
        "sex": "M",
        "premium": true,
        "summit": true,
        "created_at": "*Removed*",
        "updated_at": "*Removed*",
        "badge_type_id": 1,
        "profile_medium": "avatar/athlete/medium.png",
        "profile": "avatar/athlete/large.png",
        "friend": null,
        "follower": null
    }
}

I have managed to access the root properties I need by creating a class with properties expires_at, expires_in, access_token, refresh_token and then using the following lines of code:

using var responseStream = await response.Content.ReadAsStreamAsync();
var stravaResponse = await JsonSerializer.DeserializeAsync<Authorisation>(responseStream);

However, I need to access the id, username, firstname and lastname that come under the child object of "athelete".

Is there a good recommended way of achieving this?


Solution

  • Just add another class representing the model for athlete, then make this a property of your top-level class:

    public class Authorisation
    {
        // Root properties
            
        // Nested athlete object
        public Athlete Athlete { get; set; }
    }
    
    public class Athlete
    {
        public string Id { get; set; }
    
        public string Username { get; set; }
    
        // Other properties
    }
    

    You can then access the values as usual in C#:

    var athleteId = stravaResponse.Athlete.Id;