1

I'm trying to parse json into kotlin objects but the problem is that its key fields are numbers any idea how can parse them , I've tried serialized name but still facing problem.

The json response looks like this :

{
    "Id": [{
            "1": {
                "name": "name1",
                "class": "11a"
            }
        },
        {
            "2": {
                "name": "name2",
                "class": "11b"
            }
        }
    ]
}

I'm using gson and the main thing i'm trying to do is to store this number fields as some other string objects.

1
  • 1
    What you posted wasn't valid JSON. Changed it to Valid JSON, while still keeping your question the way it is, since it's still a valid question. Commented Apr 19, 2020 at 9:43

1 Answer 1

1

You can parse them into a list of maps, then "map" those to your data classes instead:

    val input = """{
    "Id": [{
            "1": {
                "name": "name1",
                "class": "11a"
            }
        },
        {
            "2": {
                "name": "name2",
                "class": "11b"
            }
        }
    ]
}"""

    val gson = Gson()
    val parsed: Map<String, List<Map<String, Any>>> = 
        gson.fromJson(input, (object : TypeToken<Map<String, List<Map<String, Any>>>>(){}).type)
    println(parsed["Id"]?.get(0)?.get("1")) // {name=name1, class=11a}

It will have some nasty generic signature, though.

If you're working with Kotlin, take a look at Klaxon, it will improve your experience.

Sign up to request clarification or add additional context in comments.

3 Comments

There's no countryitems in the JSON you've provided, so my example may not work as-is on your code. Are you getting the error while parsing or while fetching values?
val parsed: Map<String, List<Map<String, Any>>> = gson.fromJson(body, (object : TypeToken<Map<String, List<Map<String, Any>>>>(){}).type) val parsedvalue: Map<Any, Any> = parsed["id"]?.get(0)?.get("1) as Map<Any, Any>
thanks this fixed my problem I mapped the data further by storing it into another variable. val parsedvalue in this example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.