Search code examples
c#json.net

how to create a list of countries from a .json file from restcountries rest API?


I am trying to create a list of countries from the .json file of restcountries.

I only want the name and the population of the countries, so I define this class:

public class CountryDTO
{
    [JsonPropertyName("name.official")]
    public string Name { get; set; }

    [JsonPropertyName("population")]
    public int Population { get; set; }
}

And this is how I try to create the list of countries from the .json file:

string json = await _httpClient.GetStringAsync("https://restcountries.com/v3.1/all");


List<CountryDTO>? countries = JsonSerializer.Deserialize<List<CountryDTO>>(json);

The population is set correctly, but the name isn't.

This is the structure of one country:

{
        "name": {
            "common": "Angola",
            "official": "Republic of Angola",
            "nativeName": {
                "por": {
                    "official": "República de Angola",
                    "common": "Angola"
                }
            }
        },
        "tld": [
            ".ao"
        ],
        "cca2": "AO",
        "ccn3": "024",
        "cca3": "AGO",
        "cioc": "ANG",
        "independent": true,
        "status": "officially-assigned",
        "unMember": true,
        "currencies": {
            "AOA": {
                "name": "Angolan kwanza",
                "symbol": "Kz"
            }
        },
        "idd": {
            "root": "+2",
            "suffixes": [
                "44"
            ]
        },
        "capital": [
            "Luanda"
        ],
        "altSpellings": [
            "AO",
            "República de Angola",
            "ʁɛpublika de an'ɡɔla"
        ],
        "region": "Africa",
        "subregion": "Middle Africa",
        "languages": {
            "por": "Portuguese"
        },
        "translations": {
            "ara": {
                "official": "أنغولا",
                "common": "جمهورية أنغولا"
            },
            "bre": {
                "official": "Republik Angola",
                "common": "Angola"
            },
            "ces": {
                "official": "Angolská republika",
                "common": "Angola"
            },
            "cym": {
                "official": "Gweriniaeth Angola",
                "common": "Angola"
            },
            "deu": {
                "official": "Republik Angola",
                "common": "Angola"
            },
            "est": {
                "official": "Angola Vabariik",
                "common": "Angola"
            },
            "fin": {
                "official": "Angolan tasavalta",
                "common": "Angola"
            },
            "fra": {
                "official": "République d'Angola",
                "common": "Angola"
            },
            "hrv": {
                "official": "Republika Angola",
                "common": "Angola"
            },
            "hun": {
                "official": "Angola",
                "common": "Angola"
            },
            "ita": {
                "official": "Repubblica dell'Angola",
                "common": "Angola"
            },
            "jpn": {
                "official": "アンゴラ共和国",
                "common": "アンゴラ"
            },
            "kor": {
                "official": "앙골라 공화국",
                "common": "앙골라"
            },
            "nld": {
                "official": "Republiek Angola",
                "common": "Angola"
            },
            "per": {
                "official": "جمهوری آنگولا",
                "common": "آنگولا"
            },
            "pol": {
                "official": "Republika Angoli",
                "common": "Angola"
            },
            "por": {
                "official": "República de Angola",
                "common": "Angola"
            },
            "rus": {
                "official": "Республика Ангола",
                "common": "Ангола"
            },
            "slk": {
                "official": "Angolská republika",
                "common": "Angola"
            },
            "spa": {
                "official": "República de Angola",
                "common": "Angola"
            },
            "srp": {
                "official": "Република Ангола",
                "common": "Ангола"
            },
            "swe": {
                "official": "Republiken Angola",
                "common": "Angola"
            },
            "tur": {
                "official": "Angola Cumhuriyeti",
                "common": "Angola"
            },
            "urd": {
                "official": "جمہوریہ انگولہ",
                "common": "انگولہ"
            },
            "zho": {
                "official": "安哥拉共和国",
                "common": "安哥拉"
            }
        },
        "latlng": [
            -12.5,
            18.5
        ],
        "landlocked": false,
        "borders": [
            "COG",
            "COD",
            "ZMB",
            "NAM"
        ],
        "area": 1246700.0,
        "demonyms": {
            "eng": {
                "f": "Angolan",
                "m": "Angolan"
            },
            "fra": {
                "f": "Angolaise",
                "m": "Angolais"
            }
        },
        "flag": "🇦🇴",
        "maps": {
            "googleMaps": "https://goo.gl/maps/q42Qbf1BmQL3fuZg9",
            "openStreetMaps": "https://www.openstreetmap.org/relation/195267"
        },
        "population": 32866268,
        "gini": {
            "2018": 51.3
        },
        "fifa": "ANG",
        "car": {
            "signs": [
                "ANG"
            ],
            "side": "right"
        },
        "timezones": [
            "UTC+01:00"
        ],
        "continents": [
            "Africa"
        ],
        "flags": {
            "png": "https://flagcdn.com/w320/ao.png",
            "svg": "https://flagcdn.com/ao.svg",
            "alt": "The flag of Angola features two equal horizontal bands of red and black, with a yellow emblem at its centre. This emblem consists of a five-pointed star within the hoist-side facing half of a cogwheel that is crossed on its lower end by a machete."
        },
        "coatOfArms": {
            "png": "https://mainfacts.com/media/images/coats_of_arms/ao.png",
            "svg": "https://mainfacts.com/media/images/coats_of_arms/ao.svg"
        },
        "startOfWeek": "monday",
        "capitalInfo": {
            "latlng": [
                -8.83,
                13.22
            ]
        }
    },

How could I create a list of countries with the name and the population?

Thanks.


Solution

  • You will have to add an extra DTO:

        public class NameDetailsDTO
        {
            [JsonPropertyName("common")]
            public string Common { get; set; } = default!;
            [JsonPropertyName("official")]
            public string Official { get; set; } = default!;
        }
    
        public class CountryDTO
        {
            [JsonPropertyName("name")]
            public NameDetailsDTO DetailedName { get; set; } = default!;
    
            public string Name { get => DetailedName.Official; }
    
            [JsonPropertyName("population")]
            public int Population { get; set; }
        }
    

    This attribute [JsonPropertyName()] allows you to define a custom name for JSON properties that doesn't necessarily match the C# property name, but is not used as a parser inside the JSON.