如何使用杰克逊解析对象数组?

时间:2019-07-25 22:35:02

标签: java json jackson

我有以下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"
    }
]

我能够将JSON中的第一个对象完全反序列化为模型,其中将名称,topLevelDomain等属性映射到模型Java对象Country的属性。使用以下代码的对象:

// 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;
    }

我必须去掉后括号才能使其正常工作。但是,此方法仅反序列化第一个对象。我想获得一个Country对象的列表,并尝试像这样实现它:

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;
    }

但是这种方法不起作用。 我认为问题在于,由于所有对象都包含在数组中,因此仅凭TypeFactory中的List<Country>就无法实现这一点。有指针吗?

1 个答案:

答案 0 :(得分:0)

由于@chrylis的建议,我能够使用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;
    }