Skip to content

Instantly share code, notes, and snippets.

@ZacSweers

ZacSweers/Simple.kt

Last active Aug 8, 2019
Embed
What would you like to do?
// 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(String::class.java).nonNull()
override fun toString(): String = "GeneratedJsonAdapter(Foo)"
override fun fromJson(reader: JsonReader): Foo {
var bar: String? = null
reader.beginObject()
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.
reader.skipName()
reader.skipValue()
}
}
}
reader.endObject()
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.")
}
writer.beginObject()
writer.name("bar")
stringAdapter.toJson(writer, value.bar)
writer.endObject()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.