Skip to content

Instantly share code, notes, and snippets.

Last active May 13, 2022 20:58
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ZacSweers/c276d2cb4e02674a1f2ca9c5ea5643f9 to your computer and use it in GitHub Desktop.
// Sample JSON
// { "bar": "hello world" }
// The Foo class
@JsonClass(generateAdapter = true)
data class Foo(
val bar: String
// Generated by Moshi Kotlin Code Gen
class FooJsonAdapter(moshi: Moshi) : JsonAdapter<Foo>() {
private val options: JsonReader.Options = JsonReader.Options.of("bar")
private val stringAdapter: JsonAdapter<String> = moshi.adapter(
override fun toString(): String = "GeneratedJsonAdapter(Foo)"
override fun fromJson(reader: JsonReader): Foo {
var bar: String? = null
while (reader.hasNext()) {
when (reader.selectName(options)) {
0 -> bar = stringAdapter.fromJson(reader) ?: throw JsonDataException("Non-null value 'bar' was null at ${reader.path}")
-1 -> {
// Unknown name, skip it.
var result = Foo(
bar = bar ?: throw JsonDataException("Required property 'bar' missing at ${reader.path}"))
return result
override fun toJson(writer: JsonWriter, value: Foo?) {
if (value == null) {
throw NullPointerException("value was null! Wrap in .nullSafe() to write nullable values.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment