How to use the data type java.util.UUID in Moshi?

Viewed 252

I used the data type java.util.UUID in my data models and I have used Moshi for serialization. But I encountered an error saying that "Platform class java.util.UUID requires explicit JsonAdapter to be registered"

I have gone through the documentation of Moshi for writing custom adapters and I tried to replicate it accordingly. I wrote an adapter and added it to a moshi instance. But still I encounter the same error .

Adapter

class UUIDAdapter {
    @ToJson
    fun toJson(value:java.util.UUID):java.util.UUID{
        return value
    }
    @FromJson
    fun fromJson(value: String):java.util.UUID{
        return java.util.UUID.fromString(value)
    }
}

Model

@JsonClass(generateAdapter = true)
data class AddWorkspace(
    @Json(name = "user_id")
    val user_id: UUID,
    @Json(name = "name")
    val name:String,
    @Json(name = "descp")
    val descp:String,
    @Json(name = "created_at")
    val created_at:String
)

Moshi

private val moshi = Moshi.Builder()
        .add(UUIDAdapter())
        .build()

    private val retrofitBuilder = Retrofit.Builder()
        .baseUrl(baseUrl)
        .addConverterFactory(MoshiConverterFactory.create(moshi))

What else am I missing so that I can use the adapter correctly ?

Edit : Well, the methods toJson and fromJson are not being called in the first place. I tried to implement the JsonAdapter class and override the methods toJson and fromJson, but the issue I face here is that in case of the method toJson, I need to send a java.util.UUID value, but the JsonWriter cannot write a value of such data type. Please suggest me a way to work my way through this. Thanks :)

UUID adapter

class UUIDAdapter:JsonAdapter<UUID>(){
    @FromJson
    override fun fromJson(reader: JsonReader): UUID? {
        return UUID.fromString(reader.readJsonValue().toString())
    }

    @ToJson
    override fun toJson(writer: JsonWriter, value: UUID?) {
        writer.jsonValue(value)
    }
}
2 Answers

You're so close. Change the @ToJson to this:

@ToJson
fun toJson(value:java.util.UUID): String {
    return value.toString()
}

as Jesse described just use:

class UuidAdapter {
    @FromJson
    fun fromJson(uuid: String): UUID = UUID.fromString(uuid)

    @ToJson
    fun toJson(value: UUID): String = value.toString()
}
Related