I am making a geography app, where people can look up a list of countries, search for a specific country and get a country's info such as Language, Capital, etc.
My issue is parsing my Okhttp Response. I have seen some tutorials on how to do it but every one of them is working with a response that seem to start with "" { "key" : {...} } "" where as my response starts with "" [ {...}, {...}, {...} ] "" each bracket pair representing a country.
The link to test here: https://restcountries.com/v3.1/independent?status=true
Right now I am simplifying the request to only work with one country: url = "https://restcountries.com/v3.1/name/canada"
where now I would just like as a starting point to get to display the "name" -> "common" - > "Canada"
This is my code:
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
private val client = OkHttpClient()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val url = "https://restcountries.com/v3.1/name/canada"
val request = Request.Builder()
.url(url)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) { println("error") }
override fun onResponse(call: Call, response: Response) {
countryData = response.body?.string().toString()
println(countryData)
val gson = GsonBuilder().create()
//first method tried
val countryName = gson.fromJson(countryData, Country::class.java)
// second method tried
val enums: Array<Country> = gson.fromJson(
countryData,
Array<Country>::class.java
)
}
})
}
}
class Country(val name : List<String>) {
}
But I get the following error: Empty list doesn't contain element at index 0.
-> Eventually this would need to go into a recycler view to display the list of Countries and their respective info. -> Bonus: If anyone also knows a way to reorder by Alphabet as that API response doesn't give the countries by alphabet order (eg: the first country is Guatemala which doesn't start with an "A")
The Json response from my example looks like this:
[
{
"name": {
"common": "Canada",
"official": "Canada",
"nativeName": {
"eng": {
"official": "Canada",
"common": "Canada"
},
"fra": {
"official": "Canada",
"common": "Canada"
}
}
},
"tld": [],
"cca2": "CA",
"ccn3": "124",
"cca3": "CAN",
"cioc": "CAN",
"independent": true,
"status": "officially-assigned",
"unMember": true,
"currencies": {},
"idd": {},
"capital": [
"Ottawa"
],
"altSpellings": [],
"region": "Americas",
"subregion": "North America",
"languages": {},
"translations": {},
"latlng": [],
"landlocked": false,
"borders": [],
"area": 9984670,
"demonyms": {},
"flag": "",
"maps": {},
"population": 38005238,
"gini": {},
"fifa": "CAN",
"car": {},
"timezones": [],
"continents": [],
"flags": {},
"coatOfArms": {},
"startOfWeek": "sunday",
"capitalInfo": {},
"postalCode": {}
}
]