Home > Mobile >  Constructing Kotlin classes for using Gson to convert json response to class
Constructing Kotlin classes for using Gson to convert json response to class

Time:09-17

I am beginning to learn Android development, and at the moment I am focusing on how to consume REST API's. The service that I am experimenting with (The Movie Database) provides a response of the form:

{
    "certifications": {
        "CA": [
            {
                "certification": "G",
                "meaning": "All ages.",
                "order": 1
            },
            ...
        ],
        "NL": [
            {
                "certification": "AL",
                "meaning": "All ages.",
                "order": 1
            },
            ...
        ],
        ...
    }
}

There are quite a long list of objects contained in the list (CA, NL, EN, etc.) but all of these objects contain the same thing - a list of objects of the exact same structure. Any of the online JSON to Kotlin class converters that I have tried want to create individual classes for each object which to me seems wasteful.

I currently have this class:

class Certifications {
    var certifications: List<Country>? = null
}

class Country {
    var country: String? = null
    var ratings: List<Certification>? = null
}

class Certification {
    var certification: String? = null
    var meaning: String? = null
    var order: Int = 0
}

Attempting this val thing = gson.fromJson(body, Certifications::class.java) results in Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 20 path $.certifications.

CodePudding user response:

This :

class Certifications {
    var certifications: List<Country>? = null
}

Should be something like :

class Certifications {
    var certifications: Map<String, <List<Certification>>? = null
}

Where the String is the code "NL" & "CA" - or if you already have a custom type adapter you could do Map<Country, <List<Certification>> - but I'm unsure if you have this setup.

  • Related