Lasse Magnussen
12/08/2022, 11:33 AM{
"title": "Some title",
"description": "Description of something",
"amount": 1000,
"currency": "NOK",
"metadata": {
"more": "stuff"
}
}
I’d like to unflatten amount
and currency
into a its own object when deserialising:
data class Item(val title: String, val description: String, val money: Money, val metadata: MetaData)
data class Money(val amount: Int, val currency: String)
Is this doable in a generic-ish way in Moshi? I’d like for that to extend to any Retrofit response object we deem worthy.
If no, I guess the alternative would be the less neat:
data class Item(val title: String, val description: String, val amount: Int, val currency String, val metadata: MetaData) {
val money: Money = Money(amount, currency)
}
which I’d like to avoid.Benoit Quenaudon
12/08/2022, 11:45 AMBenoit Quenaudon
12/08/2022, 11:46 AMLasse Magnussen
12/08/2022, 11:56 AMBenoit Quenaudon
12/08/2022, 11:57 AMBenoit Quenaudon
12/08/2022, 11:58 AMval moshi = Moshi.Builder()
.add(CardAdapter())
.build()
and have a unique Moshi instance across your whole app, that’s all you needLasse Magnussen
12/08/2022, 12:32 PMCardAdapter
look like? It needs to handle generic-ish objects and it needs to somehow extract the two fields it needs and put into the respective val in the data class.
And the data class could be 1 of many different ones.
data class SomeOtherResponse(val index: Int, val money: Money)
f.ex.
It needs to be generic, it needs to delegate the rest of the fields to other adapters.Benoit Quenaudon
12/08/2022, 12:34 PMBenoit Quenaudon
12/08/2022, 12:35 PMLasse Magnussen
12/08/2022, 12:36 PMLasse Magnussen
12/08/2022, 12:41 PM@Wrapped
or something that could signal that this field should get its data from its “parent” (really it’ll be siblings), but I’m struggling to find a neat way to do that.Benoit Quenaudon
12/08/2022, 1:07 PM@AlwaysSerializeNulls
on all parents, and then hook my logic somewhereBenoit Quenaudon
12/08/2022, 1:08 PMZac Sweers
12/08/2022, 5:11 PMItem
and need to manually manage those keys yourself to create the intermediate Money
typeZac Sweers
12/08/2022, 5:12 PMreadJsonValue()
API, which will just give you back a Map<String, Any?> of everything in the current blobjessewilson
12/09/2022, 2:16 AMbeginFlatten()
:
https://github.com/square/moshi/blob/6f9223af8c1a69e5707e2ad8d5088956784ae8d5/moshi/src/main/java/com/squareup/moshi/JsonWriter.kt#L501Lasse Magnussen
12/09/2022, 10:27 AMbeginFlatten
to work, but I managed to come up with something.
Feel free to use it however you like.
Public domain.