ansman/kotshi

Generate JsonAdapter for ENUMS

Closed this issue · 2 comments

these days we have type fields for almost every object we receive from webservers.

and in my opinion enums represent types in the best form. but currently Kotshi only supports data classes and it has made us to write tons of adapters just for our enum types.

a sample enum class used in our production app is like this:

enum class CouponType(
    val type: String
) {
    @Json(name = "")
    NONE(""),
    @Json(name = "discount_percent")
    DISCOUNT_PERCENT("discount_percent"),
    @Json(name = "discount_amount")
    DISCOUNT_AMOUNT("discount_amount"),
    @Json(name = "reward_item")
    REWARD_ITEM("reward_item")
}

and the adapter:

class CouponTypeJsonAdapter {
    @ToJson
    fun toJson(
        type: CouponType
    ) =
        type.type

    @FromJson
    fun fromJson(type: String): CouponType =
        when (type) {
            CouponType.DISCOUNT_AMOUNT.type ->
                CouponType.DISCOUNT_AMOUNT
            CouponType.DISCOUNT_PERCENT.type ->
                CouponType.DISCOUNT_PERCENT
            CouponType.REWARD_ITEM.type ->
                CouponType.REWARD_ITEM
            else ->
                CouponType.NONE
        }

}

I tried to submit a PR but I'm not good with the tools used in the processor but happy to help in any way that I can.

Enums are supported out of the box by Moshi, no adapters are needed.

I'm gonna close this out, if you have any other issues or questions I'll reopen it.