Slaknation
Slaknation

Reputation: 1926

Kotlin: Passing HashMap with multiple value types into function

I have a HashMap that looks like this:

{
    "name": "George",
    "weeks": [
        {
            "checked": true,
            "days": [
                {
                    "checked": true,
                    "exercises": [
                        {
                            "exercise": "Bench Press",
                            "sets": [
                                {
                                    "weight": 300,
                                    "reps": 20
                                },
                                {
                                    "weight": 400,
                                    "reps": 30
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

So I thought I could pass it into the constructor of a class like so:

data class Gainer(val weeks: ArrayList<HashMap<String, ArrayList<HashMap<String, ArrayList<HashMap<String, ArrayList<HashMap<String, Long>>>>>>>>?, val name: String?) {

However, I am getting this error:

java.lang.RuntimeException: Could not deserialize object. Expected a List, but got a class java.lang.String (found in field 'weeks.[0].days.[0].exercises.[0].exercise')

I am guessing I get this error because when I specify Hashmap<String, ArrayList ...> It is expecting String as the key type and ArrayList as the Value type. However, sometimes I set a boolean as one of the values and an ArrayList as a different value. I'm not sure how to specify multiple value types.

edit: What I am passing in isn't actually json data like what is shown. It is technically a documentSnapshot. I am getting it from Firestore. Sorry, I should have clarified that better.

Upvotes: 1

Views: 2530

Answers (2)

Zain Ul Abideen
Zain Ul Abideen

Reputation: 1602

one thing that might be helpful from Java perspective to handle multi-level hashmap;

Map<String, Object> myMap = new HashMap<String, Object>()

as in java Object is parent class for all, so that passing Object as value in map can cater any level of map.

Upvotes: 0

Henrique Horbovyi
Henrique Horbovyi

Reputation: 96

I always use Json to Kotlin Class Plugin

Json to Kotlin Class is a plugin that make it easier to create POJOs from json file, and it will solve your problem creating your data classes.

You can see the usage in this gif:

Json to Kotlin Class Plugin gif

You should download and add on your Android Studio or IntelliJ IDE as a plugin
Here is the link for download ~> Json to Kotlin Class

It saves my life!

Upvotes: 4

Related Questions