how can I do a sealed class that contains a data c...
# getting-started
b
how can I do a sealed class that contains a data class and a String (that's for a Json file where I can have either of these two)
r
You can't, but you can make a wrapper for
String
.
Copy code
sealed class Json<T>(val value: T)
class JsonElem(value: String) : Json<String>(value)
class JsonArray(value: List<Json<*>>) : Json<List<Json<*>>>(value)
class JsonObject(value: Map<String, Json<*>>): Json<Map<String, Json<*>>>(value)
b
I have to see if Moshi handles that
thx
k
You can use custom adapters in Moshi to serialize it however you want
b
yes that's what I am trying but I have issues wrapping my head around how I'm supposed to get something that can return one of the two types
@kevinmost do you have any reference for moshi where polymorphic is applied to a type inside a file?
I can only find examples where it is polymorphic on file
k
generally to make "polymorphic JSON", you'd have some sort of "type" string to go along with the actual data object, and you'd switch on that string to determine what serializer/deserializer logic to use
b
yeah in that format (that I don't control), I get: [{"query":"foo", "to":"bar"}, "OR", {…}]
k
I'm not too familiar with Moshi, honestly, but Gson's TypeAdapterFactory would let you peer into the JSON before you decide what logic to use
b
I should just switch my JSON lib then
it reminds me of all those web framework, they all show you how easy it is to do a todo list, and then they don't tell you that anything more complex will take you days of tweaking…
k
you shouldn't do that. Moshi can do everything Gson can and more. What you're trying to do is not standard with JSON, and thus is clunky to do in any framework. JSON that's polymorphic without a "type" string sitting next to it is just objectively bad API design
you're gonna switch to Gson, implement TypeAdapterFactory, and realize that it's at least as weird via Gson as it is via Moshi
b
hmm
I wanted to handle that field for the sake of completeness, I will probably just ignore it…
s
dont forget to read the recent changelog, moshi added a polymorphicjsonadapter for event sourcing, not switched yet since I built my _type adapter a while ago
b
thx. What I'm lacking mostly is really examples on how to use that…