Created
December 12, 2016 01:07
-
-
Save ChainsDD/07c6b52837a2fa0622c93df07a92f48d to your computer and use it in GitHub Desktop.
Moshi custom type adapter on Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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