Mr. Dev Mr. Dev - 5 months ago 21
JSON Question

Parsing JSON Array of one object inside another JSON Array using Swift 3

I am really new to Swift and iOS and I am learning on working with REST API calls. While the call works and I am able to get the data. I can't see to parse the entire data correctly. I am trying to get the countries and their calling codes. I was successful in parsing the country names and storing them in an array but for some reason I can't parse the array object that contains the calling code for each country.

Here's the JSON response that I get from the API

[
{
name: "Afghanistan",
topLevelDomain: [
".af"
],
alpha2Code: "AF",
alpha3Code: "AFG",
callingCodes: [
"93"
],
capital: "Kabul",
altSpellings: [
"AF",
"Afġānistān"
],
region: "Asia",
subregion: "Southern Asia",
population: 27657145,
latlng: [
33,
65
],
demonym: "Afghan",
area: 652230,
gini: 27.8,
timezones: [
"UTC+04:30"
],
borders: [
"IRN",
"PAK",
"TKM",
"UZB",
"TJK",
"CHN"
],
nativeName: "افغانستان",
numericCode: "004",
currencies: [
{
code: "AFN",
name: "Afghan afghani",
symbol: "؋"
}
],
languages: [
{
iso639_1: "ps",
iso639_2: "pus",
name: "Pashto",
nativeName: "پښتو"
},
{
iso639_1: "uz",
iso639_2: "uzb",
name: "Uzbek",
nativeName: "Oʻzbek"
},
{
iso639_1: "tk",
iso639_2: "tuk",
name: "Turkmen",
nativeName: "Türkmen"
}
],
translations: {
de: "Afghanistan",
es: "Afganistán",
fr: "Afghanistan",
ja: "アフガニスタン",
it: "Afghanistan",
br: "Afeganistão",
pt: "Afeganistão"
},
flag: "https://restcountries.eu/data/afg.svg",
regionalBlocs: [
{
acronym: "SAARC",
name: "South Asian Association for Regional Cooperation",
otherAcronyms: [ ],
otherNames: [ ]
}
]
},
.....

]


Here's what I have tried

func getData2() {
let urlString = "https://restcountries.eu/rest/v2/all"

let url = URL(string: urlString)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
if error != nil {
print(error!)
} else {
do {

let parsedData = try JSONSerialization.jsonObject(with: data!) as! [[String:Any]]
// let countryNames = parsedData.flatMap { $0["name"] as? String }
//let countryCodes = parsedData.flatMap { $0["callingCodes"] as? String }

for country in parsedData {

if let name = country["name"] as? String {
self.countryNamesArray.append(name)
}
if let capital = country["capital"] as? String {
print(capital)
}

if let code = country["callingCodes"] as? [[String:Any]] {

print("Got Here: ", code)
// why I get nothing here?

for tag in code {
print(tag)
// I get nothing here as well
}
}
//self.countryCodesArray.append(code)
}
}

//print(self.countryNamesArray)
// print(self.countryCodesArray)
self.searchTextField.filterStrings(self.countryNamesArray)

} catch let error as NSError {
print(error)
}
}

}.resume()
}


Coming from an android background, I thought it would be possible to index the array and get the item on that position, however that doesn't work as well. Please don't mind as I am just a beginner and trying my best to learn Swift.

Any help would be appreciated.

Thanks

Answer Source

Make this change to your code

 if let code = country["callingCodes"] as? [String] {

                      // if you want only first index use this
                      if code.count > 0{
                        let countryCode = code[0]
                        print("First index Country Code",countryCode)
                        self.countryCodesArray.append(countryCode)
                      }
}