3

I want to retrieve a collection of football leagues from an external api. The response from the server comes as shown below:

{
"api": {
    "results": 1496,
    "leagues": [
        {
            "league_id": 1,
            .....

The returned object constists of an "api" field which hold "results" and "leagues". I would like deserialize the code and map it to League class objects in my code.

var jsonString = await ExecuteUrlAsync(filePath, url);

var results = JsonConvert.DeserializeObject<IEnumerable<LeagueEntity>>(jsonString);

jsonString is correct, but when the program hits second line I get an exception:

Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.IEnumerable".

I need to get to the "leagues" field in JSON file, and ignore the rest of the response. How to achieve that?

2
  • Is it Syste.Text.Json or Json.NET api? How does LeagueEntity look like? Commented Mar 16, 2020 at 19:07
  • post a complete json sample and i could tell you how to do it with strongly typed model Commented Mar 17, 2020 at 0:03

1 Answer 1

1

Assuming your LeagueEntity corresponds to the api.leagues[*] objects, you can use JsonConvert.DeserializeAnonymousType() to pick out and deserialize the interesting portions of the JSON:

var leagues = JsonConvert.DeserializeAnonymousType(jsonString, 
                                                   new { api = new { leagues = default(List<LeagueEntity>) } })
    ?.api?.leagues;

This avoids the need to create an explicit data model for the api.leagues container objects. It should also be more efficient than pre-loading into a JToken hierarchy, then as a second step selecting and deserializing the api.leagues array.

Demo fiddle here.

(Alternatively, you could auto-generate a complete data model for the entire JSON using one of the answers from How to auto-generate a C# class file from a JSON string.)

Sign up to request clarification or add additional context in comments.

Comments

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.