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?

dbc
  • 104,963
  • 20
  • 228
  • 340
Bulchsu
  • 580
  • 11
  • 33

1 Answers1

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.)

dbc
  • 104,963
  • 20
  • 228
  • 340