Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Moshi custom type adapter on Kotlin
class RedditLink(
val author: String,
val likes: RedditLikes,
val title: String,
val score: Int
)
enum class RedditLikes {
UP, DOWN, NONE
}
class LikesAdapter {
@FromJson fun fromJson(likes: String): RedditLikes {
Log.d("LikesAdapter", "I was called!!")
when (likes) {
"true" -> return RedditLikes.UP
"false" -> return RedditLikes.DOWN
"null" -> return RedditLikes.NONE
else -> {
throw JsonDataException("likes could not be parsed: " + likes)
}
}
}
@ToJson fun toJson(likes: RedditLikes) = when(likes) {
RedditLikes.UP -> "true"
RedditLikes.DOWN -> "false"
RedditLikes.NONE -> "null"
}
}
val moshi = Moshi.Builder()
.add(LikesAdapter())
.build()
val retrofit = Retrofit.Builder()
.baseUrl("https://www.reddit.com")
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment