How to map numbered JSON fields to a list using Kotlinx Serialization


I’m working with an API (TheMealDB) that returns ingredients in this format:

{
"strIngredient1": "Salmon",
"strIngredient2": "Soy Sauce",
"strIngredient3": "Sugar",
...
"strIngredient20": null,
"strMeasure1": "2 fillets",
"strMeasure2": "3 tbsp",
"strMeasure3": "1 tbsp",
...
}

So instead of returning something like:

ingredients: [ { name: "Salmon", measure: "2 fillets" } m

it exposes fixed numbered fields (strIngredient1..20, strMeasure1..20).

The common approach I see is something like:

for (i in 1..20) {

      val ingredient = json\["strIngredient$i"\]?.jsonPrimitive?.contentOrNull

      val measure = json\["strMeasure$i"\]?.jsonPrimitive?.contentOrNull

}

But I’m wondering if there is a more idiomatic solution using kotlinx.serialization or Kotlin in general.

For example:

using a custom serializer, mapping dynamic JSON keys automatically

avoiding hardcoding the 1..20 range

Is there a cleaner pattern for handling APIs that expose numbered fields like this?

0
Mar 7 at 12:56 AM
User AvatarVivek Modi
#android#kotlin#ktor#kotlinx.serialization

No answer found for this question yet.