1

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?

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

Comments

0

Just to add to what Noah has added, if you are using Visual Studio (not sure about VS Code) you can use:

Edit >> Paste Special >> Paste JSON as Classes

in the menu and it will create the classes required to be able to deserialise any (valid) JSON you paste. Once you have this you can deserialise using that class and access it's members like any other class.

1 Comment

Thanks for the advice, I'll give that a try

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.