Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. sealed class Animal {
  2. data class Dog(val isGoodBoy: Boolean) : Animal()
  3. data class Cat(val remainingLives: Int) : Animal()
  4. }
  5.  
  6. private val moshi = Moshi.Builder()
  7. .build()
  8.  
  9. @Test
  10. fun test() {
  11. val animal: Animal = Animal.Dog(true)
  12. println(moshi.adapter(Animal::class.java).toJson(animal))
  13. }
  14.  
  15. class AnimalAdapter {
  16. @ToJson
  17. fun toJson(jsonWriter: JsonWriter, animal: Animal) {
  18. jsonWriter.beginObject()
  19. jsonWriter.name("type")
  20. when (animal) {
  21. is Animal.Dog -> jsonWriter.value("dog")
  22. is Animal.Cat -> jsonWriter.value("cat")
  23. }
  24.  
  25. jsonWriter.name("properties").beginObject()
  26. when (animal) {
  27. is Animal.Dog -> jsonWriter.name("isGoodBoy").value(animal.isGoodBoy)
  28. is Animal.Cat -> jsonWriter.name("remainingLives").value(animal.remainingLives)
  29. }
  30. jsonWriter.endObject().endObject()
  31. }
  32.  
  33. ....
  34. }
  35.  
  36. {
  37. "type" : "cat",
  38. "properties" : {
  39. "remainingLives" : 6
  40. }
  41. }
  42.  
  43. {
  44. "type" : "dog",
  45. "properties" : {
  46. "isGoodBoy" : true
  47. }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement