0

I have the following json :

[
    {
        "name": "Australia",
        "topLevelDomain": [
            ".au"
        ],
        "alpha2Code": "AU",
        "alpha3Code": "AUS",
        "callingCodes": [
            "61"
        ],
        "capital": "Canberra",
        "altSpellings": [
            "AU"
        ],
        "region": "Oceania",
        "subregion": "Australia and New Zealand",
        "population": 24117360,
        "latlng": [
            -27.0,
            133.0
        ],
        "demonym": "Australian",
        "area": 7692024.0,
        "gini": 30.5,
        "timezones": [
            "UTC+05:00",
            "UTC+06:30",
            "UTC+07:00",
            "UTC+08:00",
            "UTC+09:30",
            "UTC+10:00",
            "UTC+10:30",
            "UTC+11:30"
        ],
        "borders": [],
        "nativeName": "Australia",
        "numericCode": "036",
        "currencies": [
            {
                "code": "AUD",
                "name": "Australian dollar",
                "symbol": "$"
            }
        ],
        "languages": [
            {
                "iso639_1": "en",
                "iso639_2": "eng",
                "name": "English",
                "nativeName": "English"
            }
        ],
        "translations": {
            "de": "Australien",
            "es": "Australia",
            "fr": "Australie",
            "ja": "オーストラリア",
            "it": "Australia",
            "br": "Austrália",
            "pt": "Austrália",
            "nl": "Australië",
            "hr": "Australija",
            "fa": "استرالیا"
        },
        "flag": "https://restcountries.eu/data/aus.svg",
        "regionalBlocs": [],
        "cioc": "AUS"
    },
    {
        "name": "Brazil",
        "topLevelDomain": [
            ".br"
        ],
        "alpha2Code": "BR",
        "alpha3Code": "BRA",
        "callingCodes": [
            "55"
        ],
        "capital": "Brasília",
        "altSpellings": [
            "BR",
            "Brasil",
            "Federative Republic of Brazil",
            "República Federativa do Brasil"
        ],
        "region": "Americas",
        "subregion": "South America",
        "population": 206135893,
        "latlng": [
            -10.0,
            -55.0
        ],
        "demonym": "Brazilian",
        "area": 8515767.0,
        "gini": 54.7,
        "timezones": [
            "UTC-05:00",
            "UTC-04:00",
            "UTC-03:00",
            "UTC-02:00"
        ],
        "borders": [
            "ARG",
            "BOL",
            "COL",
            "GUF",
            "GUY",
            "PRY",
            "PER",
            "SUR",
            "URY",
            "VEN"
        ],
        "nativeName": "Brasil",
        "numericCode": "076",
        "currencies": [
            {
                "code": "BRL",
                "name": "Brazilian real",
                "symbol": "R$"
            }
        ],
        "languages": [
            {
                "iso639_1": "pt",
                "iso639_2": "por",
                "name": "Portuguese",
                "nativeName": "Português"
            }
        ],
        "translations": {
            "de": "Brasilien",
            "es": "Brasil",
            "fr": "Brésil",
            "ja": "ブラジル",
            "it": "Brasile",
            "br": "Brasil",
            "pt": "Brasil",
            "nl": "Brazilië",
            "hr": "Brazil",
            "fa": "برزیل"
        },
        "flag": "https://restcountries.eu/data/bra.svg",
        "regionalBlocs": [
            {
                "acronym": "USAN",
                "name": "Union of South American Nations",
                "otherAcronyms": [
                    "UNASUR",
                    "UNASUL",
                    "UZAN"
                ],
                "otherNames": [
                    "Unión de Naciones Suramericanas",
                    "União de Nações Sul-Americanas",
                    "Unie van Zuid-Amerikaanse Naties",
                    "South American Union"
                ]
            }
        ],
        "cioc": "BRA"
    },
    {
        "name": "China",
        "topLevelDomain": [
            ".cn"
        ],
        "alpha2Code": "CN",
        "alpha3Code": "CHN",
        "callingCodes": [
            "86"
        ],
        "capital": "Beijing",
        "altSpellings": [
            "CN",
            "Zhōngguó",
            "Zhongguo",
            "Zhonghua",
            "People's Republic of China",
            "中华人民共和国",
            "Zhōnghuá Rénmín Gònghéguó"
        ],
        "region": "Asia",
        "subregion": "Eastern Asia",
        "population": 1377422166,
        "latlng": [
            35.0,
            105.0
        ],
        "demonym": "Chinese",
        "area": 9640011.0,
        "gini": 47.0,
        "timezones": [
            "UTC+08:00"
        ],
        "borders": [
            "AFG",
            "BTN",
            "MMR",
            "HKG",
            "IND",
            "KAZ",
            "PRK",
            "KGZ",
            "LAO",
            "MAC",
            "MNG",
            "PAK",
            "RUS",
            "TJK",
            "VNM"
        ],
        "nativeName": "中国",
        "numericCode": "156",
        "currencies": [
            {
                "code": "CNY",
                "name": "Chinese yuan",
                "symbol": "¥"
            }
        ],
        "languages": [
            {
                "iso639_1": "zh",
                "iso639_2": "zho",
                "name": "Chinese",
                "nativeName": "中文 (Zhōngwén)"
            }
        ],
        "translations": {
            "de": "China",
            "es": "China",
            "fr": "Chine",
            "ja": "中国",
            "it": "Cina",
            "br": "China",
            "pt": "China",
            "nl": "China",
            "hr": "Kina",
            "fa": "چین"
        },
        "flag": "https://restcountries.eu/data/chn.svg",
        "regionalBlocs": [],
        "cioc": "CHN"
    },
    {
        "name": "United Kingdom of Great Britain and Northern Ireland",
        "topLevelDomain": [
            ".uk"
        ],
        "alpha2Code": "GB",
        "alpha3Code": "GBR",
        "callingCodes": [
            "44"
        ],
        "capital": "London",
        "altSpellings": [
            "GB",
            "UK",
            "Great Britain"
        ],
        "region": "Europe",
        "subregion": "Northern Europe",
        "population": 65110000,
        "latlng": [
            54.0,
            -2.0
        ],
        "demonym": "British",
        "area": 242900.0,
        "gini": 34.0,
        "timezones": [
            "UTC-08:00",
            "UTC-05:00",
            "UTC-04:00",
            "UTC-03:00",
            "UTC-02:00",
            "UTC",
            "UTC+01:00",
            "UTC+02:00",
            "UTC+06:00"
        ],
        "borders": [
            "IRL"
        ],
        "nativeName": "United Kingdom",
        "numericCode": "826",
        "currencies": [
            {
                "code": "GBP",
                "name": "British pound",
                "symbol": "£"
            }
        ],
        "languages": [
            {
                "iso639_1": "en",
                "iso639_2": "eng",
                "name": "English",
                "nativeName": "English"
            }
        ],
        "translations": {
            "de": "Vereinigtes Königreich",
            "es": "Reino Unido",
            "fr": "Royaume-Uni",
            "ja": "イギリス",
            "it": "Regno Unito",
            "br": "Reino Unido",
            "pt": "Reino Unido",
            "nl": "Verenigd Koninkrijk",
            "hr": "Ujedinjeno Kraljevstvo",
            "fa": "بریتانیای کبیر و ایرلند شمالی"
        },
        "flag": "https://restcountries.eu/data/gbr.svg",
        "regionalBlocs": [
            {
                "acronym": "EU",
                "name": "European Union",
                "otherAcronyms": [],
                "otherNames": []
            }
        ],
        "cioc": "GBR"
    },
    {
        "name": "United States of America",
        "topLevelDomain": [
            ".us"
        ],
        "alpha2Code": "US",
        "alpha3Code": "USA",
        "callingCodes": [
            "1"
        ],
        "capital": "Washington, D.C.",
        "altSpellings": [
            "US",
            "USA",
            "United States of America"
        ],
        "region": "Americas",
        "subregion": "Northern America",
        "population": 323947000,
        "latlng": [
            38.0,
            -97.0
        ],
        "demonym": "American",
        "area": 9629091.0,
        "gini": 48.0,
        "timezones": [
            "UTC-12:00",
            "UTC-11:00",
            "UTC-10:00",
            "UTC-09:00",
            "UTC-08:00",
            "UTC-07:00",
            "UTC-06:00",
            "UTC-05:00",
            "UTC-04:00",
            "UTC+10:00",
            "UTC+12:00"
        ],
        "borders": [
            "CAN",
            "MEX"
        ],
        "nativeName": "United States",
        "numericCode": "840",
        "currencies": [
            {
                "code": "USD",
                "name": "United States dollar",
                "symbol": "$"
            }
        ],
        "languages": [
            {
                "iso639_1": "en",
                "iso639_2": "eng",
                "name": "English",
                "nativeName": "English"
            }
        ],
        "translations": {
            "de": "Vereinigte Staaten von Amerika",
            "es": "Estados Unidos",
            "fr": "États-Unis",
            "ja": "アメリカ合衆国",
            "it": "Stati Uniti D'America",
            "br": "Estados Unidos",
            "pt": "Estados Unidos",
            "nl": "Verenigde Staten",
            "hr": "Sjedinjene Američke Države",
            "fa": "ایالات متحده آمریکا"
        },
        "flag": "https://restcountries.eu/data/usa.svg",
        "regionalBlocs": [
            {
                "acronym": "NAFTA",
                "name": "North American Free Trade Agreement",
                "otherAcronyms": [],
                "otherNames": [
                    "Tratado de Libre Comercio de América del Norte",
                    "Accord de Libre-échange Nord-Américain"
                ]
            }
        ],
        "cioc": "USA"
    }
]

I am able to de serialize the first object in the JSON to a model perfectly where properties like name, topLevelDomain etc are mapped to properties of model java object Country. object using the following code :

// json arg is the complete json mentioned above
private Country jsonToCountry(String json){ 
        Country country = null;
        ObjectMapper mapper = new ObjectMapper();
        try {
            json = json.substring(1,json.length()-2);
            country  = mapper.readValue(json, Country.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return country;
    }

I had to remove the the trailing brackets to make it work. However, this method de serializes only the first object. I want to get a list of Country objects and trying to achieve it like this :

private List<Country> jsonToCountry(String json){
        List<Country> countryList = null;
        ObjectMapper mapper = new ObjectMapper();
        try {
            json = (json.indexOf("[") == 0)? json.substring(1,json.length()-2):json;
            TypeFactory typeFactory = mapper.getTypeFactory();
            countryList = mapper.readValue(json, typeFactory.constructCollectionType(List.class, Country.class));
        } catch (IOException e) {
            e.printStackTrace();
        }
return countryList;
    }

This approach however doesn't work. I think the problem is that since all objects are enclosed in an array I cannot achieve this merely with a TypeFactory of List<Country>. Any pointers ?

2
  • 1
    I think you'll need to use a TypeReference to deserialize a generic collection. Commented Jul 25, 2019 at 22:49
  • Have you tried using the com.fasterxml.jackson.core.JsonParser parser ? Commented Jul 25, 2019 at 22:59

1 Answer 1

0

Thanks to the suggestion by @chrylis , I was able to get the result results using TypeReference

private List<Country> jsonToCountryTypeRef(String json){
        ObjectMapper mapper = new ObjectMapper();
        TypeReference<List<Country>> typeRef
                = new TypeReference<List<Country>>() {};

        List<Country> o = null;
        try {
            o = mapper.readValue(json, typeRef);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return o;
    }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.