Skip to content

Instantly share code, notes, and snippets.

@swankjesse
Created May 14, 2017 17:15
Show Gist options
  • Save swankjesse/61354fd0a20bf56072f6a1d0c82fb9fc to your computer and use it in GitHub Desktop.
Save swankjesse/61354fd0a20bf56072f6a1d0c82fb9fc to your computer and use it in GitHub Desktop.
Demo how to use Moshi with Kotlin
import com.squareup.moshi.Json
import com.squareup.moshi.KotlinJsonAdapterFactory
import com.squareup.moshi.Moshi
import com.squareup.moshi.Rfc3339DateJsonAdapter
import java.util.Date
val json = """
{
"url": "https://api.github.com/repos/square/okio/issues/156",
"id": 91393390,
"number": 156,
"title": "ByteString.utf8CharSequence()",
"labels": [
{
"url": "https://api.github.com/repos/square/okio/labels/enhancement",
"id": 86454697,
"name": "enhancement",
"color": "84b6eb"
}
],
"milestone": {
"url": "https://api.github.com/repos/square/okio/milestones/2",
"id": 992290,
"title": "Icebox",
"creator": {
"url": "https://api.github.com/users/swankjesse",
"login": "swankjesse"
},
"open_issues": 12,
"closed_issues": 1,
"created_at": "2015-02-24T00:59:14.000Z"
},
"state": "open",
"created_at": "2015-06-27T00:49:40.000Z",
"body": "Would be interesting to return a `CharSequence` that's backed by the same `ByteArray`.\n"
}
"""
data class Issue(
val url: String,
val id: Long,
val number: Long,
val title: String,
val labels: List<Label> = listOf<Label>(),
val milestone: Milestone?,
val assignees: List<User> = listOf<User>(),
val state: State,
val comments: Long = 0L,
@Json(name = "created_at") val createdAt: Date,
@Json(name = "closed_at") val closedAt: Date?,
val body: String = ""
)
enum class State {
@Json(name = "open") OPEN,
@Json(name = "closed") CLOSED
}
data class Label(
val url: String,
val id: Long,
val name: String,
val color: String = "46DF1B"
)
data class Milestone(
val url: String,
val id: Long,
val title: String,
val creator: User,
@Json(name = "open_issues") val openCount: Long = 0L,
@Json(name = "closed_issues") val closedCount: Long = 0L,
@Json(name = "created_at") val createdAt: Date,
@Json(name = "due_on") val dueOn: Date?
)
data class User(val url: String, val login: String)
fun main(args: Array<String>) {
val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory)
.add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe())
.build()
val issueAdapter = moshi.adapter(Issue::class.java)
val issue = issueAdapter.fromJson(json)
println(issue)
}
@HamzaAliUpgenics
Copy link

its is similar to serializable naming in data model for retrofit with latest some extra features i think

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment