Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- sealed class Animal {
- data class Dog(val isGoodBoy: Boolean) : Animal()
- data class Cat(val remainingLives: Int) : Animal()
- }
- private val moshi = Moshi.Builder()
- .build()
- @Test
- fun test() {
- val animal: Animal = Animal.Dog(true)
- println(moshi.adapter(Animal::class.java).toJson(animal))
- }
- class AnimalAdapter {
- @ToJson
- fun toJson(jsonWriter: JsonWriter, animal: Animal) {
- jsonWriter.beginObject()
- jsonWriter.name("type")
- when (animal) {
- is Animal.Dog -> jsonWriter.value("dog")
- is Animal.Cat -> jsonWriter.value("cat")
- }
- jsonWriter.name("properties").beginObject()
- when (animal) {
- is Animal.Dog -> jsonWriter.name("isGoodBoy").value(animal.isGoodBoy)
- is Animal.Cat -> jsonWriter.name("remainingLives").value(animal.remainingLives)
- }
- jsonWriter.endObject().endObject()
- }
- ....
- }
- {
- "type" : "cat",
- "properties" : {
- "remainingLives" : 6
- }
- }
- {
- "type" : "dog",
- "properties" : {
- "isGoodBoy" : true
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement