Hello Anyone has exp with moshi when dealing with ...
# announcements
j
Hello Anyone has exp with moshi when dealing with different types on the same property? My specific use case, I have a variable that sometimes returns an object and others a boolean šŸ¤·ā€ā™‚ļø I know this must be done with adapters but I havenā€™t been able to get it to work, since all the examples I read is from a int to bool or something like that, not primitive to object Thanks in advance šŸ’Ŗ ```
d
Code example? (Have you considered
kotlinx.serialisation
šŸ˜›).
k
When using GSON, we just have 2 different nullable variables for each case. Not the best, but it worked
j
Copy code
object: {
  owner: "John Doe",
  price: false <--------- bool
},

(...)

object: {
  owner: "John Doe",
  price: { <--------- Object
      rate: 0.00420529425481,
      amount: 343
  }
},

(...)
Hereā€™s a small snippet to illustrate the use case, regarding kotlinx I havenā€™t used it as an adapter for retrofit so not sure if it is working, as for GSON it would a big change and possibly loose capability of the default values šŸ˜„
k
I wanted to switch to Moshi but co-worker didn't want to change
d
Well, this looks like sealed class territory.
k
j
Iā€™ve read, and re-read that article still havenā€™t been able to figure out,t his has to do with the Kotlin adapter which Iā€™m unable to build a working solutions :S @Dominaezzz donā€™t really get where sealed classes would be useful here?
d
What type do you want
price
to be?
j
the objectā€¦ and null if bool
d
Oh! Instead of using
null
,
false
is used.
I didn't understand that.
You can make a type adapter and check for
"false"
.
j
Thanks for your input but thatā€™s exactly what Iā€™ve been saying, if you read what Iā€™ve said you can see what my use case is, I donā€™t get the sealed classes and checking for ā€œfalseā€ would help. My issue is exactly with the adapter from boolean to object (the one I specify), Iā€™ve been searching all over the interwebz and canā€™t seem to find a good solution :S
k
I think what Dominic is saying is that by using a sealed class with a name of "price", you could have 2 different types: One that has a boolean value and another that has the items in your object
šŸ‘Œ 1
d
Copy code
class PriceAdapter(val adapter: RealPriceAdpater) {
  @ToJson fun toJson(price: Price?): String {
    return if (price != null) adapter.toJson(price) else "false"
  }

  @FromJson fun fromJson(price: String): Price? {
    if (price == "false") return null
    return adapter.fromJson(price)
  }
}
šŸ™ 1