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
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!
Most helpful comment
You should use
@JsonIt'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: