Last active
May 13, 2022 20:58
-
-
Save ZacSweers/c276d2cb4e02674a1f2ca9c5ea5643f9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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