Is there any problem with this Moshi Adapter, it d...
# squarelibraries
d
Is there any problem with this Moshi Adapter, it doesn't seem like Moshi is using it at all...
Copy code
class IdAdapter {
	private val logger = KotlinLogging.logger {}

	@FromJson
	@OdooIdentityId
	fun fromJson(value: Any): Int? = when (value) {
		is Boolean -> null
		is Double -> value.toString().toInt()
		is Int -> value
		is ArrayList<*> -> checkArrayValue(value.first()!!)
		else -> throw IllegalStateException("Non-object-non-boolean value for @OdooIdentityId field $value")
	}

	@ToJson
	fun toJson(@OdooIdentityId value: Int?): String = TODO()

	private fun checkArrayValue(value: Any): Int? = when(value) {
		is Boolean -> null
		is Double -> value.toInt()
		is Int -> value
		else -> error("Invalid Odoo identity $value")
	}
}
b
Have you registered it in your Moshi Builder?
d
Yes...
Moshi.Builder().add(IdAdapter()).build()
b
Sorry, I have had the same question from coworkers many times and it turned out to not having been registered 🙂, just thought I’d check
d
Thanks for trying 🙂!
b
Does
@OdooIdentityId value: Int?
apply the annotation to the parameter or to the type? IIRC moshi expects the type to be annotated. The example on the README is in java so it doesn’t really help lol
Ahh, probably not the case. This is what is used in the Kotlin tests
Copy code
class UppercaseJsonAdapter {
  @ToJson fun toJson(@Uppercase s: String) : String {
    return s.toUpperCase(<http://Locale.US|Locale.US>)
  }
  @FromJson @Uppercase fun fromJson(s: String) : String {
    return s.toLowerCase(<http://Locale.US|Locale.US>)
  }
}
https://github.com/square/moshi/blob/master/kotlin/tests/src/test/kotlin/com/squareup/moshi/kotlin/reflect/KotlinJsonAdapterTest.kt
Oh! Yeah, I didn’t even look into your data class 🙂