1

for two days, i am trying to figure out parsing of following json.

[
    {
        "name": "Czech Republic",
        "alpha2Code": "CZ",
        "alpha3Code": "CZE",
        "capital": "Prague",
        "subregion": "Central Europe",
        "region": "Europe",
        "regionalBlocs": [
            {
                "acronym": "EU",
                "name": "European Union"
            }
        ],
        "independent": false
    }
]

My wrapper:

public with sharing class Countries_info {

    public String name;
    public String alpha2Code;
    public String alpha3Code;
    public String capital;
    public String subregion;
    public String region;
    public List<RegionalBlocs> regionalBlocs;
    
    public class RegionalBlocs {
        public String acronym;
    }
    
    public static List<Countries_info> parse(String json) {
        return (List<Countries_info>) System.JSON.deserialize(json, List<Countries_info>.class);
    }
}

And Retriever

public with sharing class Countries_Info_Retriever {

private static final String restcountries_URL = 'https://restcountries.com/v2/all?fields=name,alpha2Code,alpha3Code,capital,region,subregion,regionalBlocs';
private static final String Get = 'GET';
public static List<Countries_info> getCountriesData() {
    List<Countries_info> countriesInfo = new List<Countries_info>();
    Http httpCallout = new Http();
    HttpRequest req = new HttpRequest();
    req.setEndpoint(restcountries_URL);
    req.setMethod(Get);

    HttpResponse countriesResponse = httpCallout.send(req);
    List<Countries_info> restcountriesResponse = Countries_info.parse(countriesResponse.getBody());

    for (Countries_info block : restcountriesResponse) {
        system.debug(block.name + ' ' + block.capital + ' ' + block.regionalBlocs.acronym);
    }
    return countriesInfo;
}

}

and for the love of god, I can't figure out how to get to that acronym. I can print out the whole List(regionalBlocs). but can't access the acronym value.

1 Answer 1

3

[] is a list of items, so you just need to access the zeroth index:

block.regionalBlocs[0].acronym

Alternatively, you can also loop over the regionalBlocs data:

for(Countries_info.RegionalBlocs regionalBloc: block.regionalBlocs) {
  system.debug(block.name + ' ' + block.capital + ' ' + regionalBloc.acronym);
}

This would get you all of the acronyms provided.

1
  • Thanks, I am so dumb :D the first version works fine. The 2nd will only get me access to regionalBloc.acronym, the others stays unreachable :-/
    – MatejN
    Sep 11 at 11:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.