Moshi: parse string with symbols to enum

Created on 15 May 2018  路  2Comments  路  Source: square/moshi

Hi
I'm trying to parse a json of bloodtypes to a kotlin enum. But I can't put O+ in kotlin enum.

I've tried overriding toString but moshi doesn't use toString to get enum members.
Would it be possible to use toString so that it could be overridden?

 @Test
    fun enumWithSymbolsAreParsed(){
        val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
        val adapter = moshi.adapter(UsingEnum::class.java)
        Assert.assertEquals(UsingEnum(KotlinEnum.Op), adapter.fromJson("""{"e": "O+"}"""))
    }

data class UsingEnum(val e: KotlinEnum)

enum class KotlinEnum(private val value: String? = null) {
    Op("O+");
    override fun toString(): String = value ?: super.toString()
}

ps: I've tried backticks and it works in unit test but android code complains that

Identifier not allowed in android projects

Most helpful comment

You should use @Json

enum class KotlinEnum(private val value: String? = null) {
    @Json(name = "O+") Op("O+")
}

It's verbose, but the idea is that this information should be statically readable, and toString() is strictly an instance method. You could reuse it if the key is statically defined too:

private const val OP_VAL = "O+"
enum class KotlinEnum(private val value: String? = null) {
    @Json(name = OP_VAL) Op(OP_VAL)
}

All 2 comments

You should use @Json

enum class KotlinEnum(private val value: String? = null) {
    @Json(name = "O+") Op("O+")
}

It's verbose, but the idea is that this information should be statically readable, and toString() is strictly an instance method. You could reuse it if the key is statically defined too:

private const val OP_VAL = "O+"
enum class KotlinEnum(private val value: String? = null) {
    @Json(name = OP_VAL) Op(OP_VAL)
}

Yeah that works. Thanks!

Was this page helpful?
0 / 5 - 0 ratings