How to Parse Json From JsonObject when Keys are not Known

Ngenge Senior
1 min readApr 26, 2021

In simple terms, how do you parse a response such as that from https://covid-api.mmediagroup.fr/v1/cases . We may be expecting the the object will have a list of countries but instead, the countries are keys.We will write a simple utility function to grab all keys from the JsonObject and iterate through the keys to generate a list of countries.

In essence, we will create a simple data class called country to hold basic Covid 19 data as follows

Great we are good to go from here. Note that each country has a JsonObject again inside with key, “All” and we will have to go through it to before getting the actual data.

Each JsonObject has a method called “keys()” which returns an iterable of strings of all the keys in the object and we can convert the iterable as a list and we will have all the keys. In summary, we got the following Kotlin code

It was short and we didn’t use any Gson or Moshi or Jackson by the way for serializing or deserializing.

Take care and until another write up again from me.

--

--