Skip to content

Instantly share code, notes, and snippets.

@ChainsDD
Created December 12, 2016 01:07
Show Gist options
  • Save ChainsDD/07c6b52837a2fa0622c93df07a92f48d to your computer and use it in GitHub Desktop.
Save ChainsDD/07c6b52837a2fa0622c93df07a92f48d to your computer and use it in GitHub Desktop.
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