1

I am receiving a Category object from Retrofit:

    data class Category(
       val id: Int,
       val title: String,
       val type: CategoryType
    )
    data class CategoryList(
       @SerializedName("categories")
       val categories: List<Category>
    )

where CategoryType is an enum class:

enum class CategoryType constructor(
    var title: String
) {
    CAT_CHICKEN("chicken"),
    CAT_PORK("pork"),
    CAT_STEAK("steak"),

    companion object {
        fun getCategoryTypeByName(text: String): CategoryType? {
            return when (text) {
                "chicken" -> CAT_CHICKEN
                "pork" -> CAT_PORK
                "steak" -> CAT_STEAK
                else -> null
            }
        }
    }
}

My api call is like this:

@GET("categs/melist/")
suspend fun getCategories(): Response<CategoryList>

How can I convert the 'type' variable that comes from the server as a string to a CategoryType object?

X. Android
  • 129
  • 2
  • 12
  • 2
    Your question is basically "How to convert the JSON response into my enum". This was already answered here: https://stackoverflow.com/a/18851314/990129 – muetzenflo Aug 23 '19 at 11:04
  • Possible duplicate of [Using Enums while parsing JSON with GSON](https://stackoverflow.com/questions/8211304/using-enums-while-parsing-json-with-gson) – a_local_nobody Aug 23 '19 at 16:02

1 Answers1

1

The problem is what your categories (for example "steak") doesn't match your enum values (for example CAT_STEAK). Use @SerializedName keyword:

enum class CategoryType constructor(var title: String) {
    @SerializedName("chicken")
    CAT_CHICKEN("chicken"),
    @SerializedName("pork")
    CAT_PORK("pork"),
    @SerializedName("steak")
    CAT_STEAK("steak"),

    companion object {
        fun getCategoryTypeByName(text: String): CategoryType? {
            return when (text) {
                "chicken" -> CAT_CHICKEN
                "pork" -> CAT_PORK
                "steak" -> CAT_STEAK
                else -> null
            }
        }
    }
}
Peter Staranchuk
  • 1,343
  • 3
  • 14
  • 29