Reputation: 115
I'm using Moshi for an Android App, but when the payload change for any reason, example: the backend add a new object type, the app will crash because I need to tell Moshi to get this new object type.
return Moshi.Builder()
.add(Adapter1())
.add(PolymorphicJsonAdapterFactory
.of(BaseClass::class.java, "baseclass")
.withSubtype(EntityOne::class.java, "entityone")
.withSubtype(EntityTwo::class.java, "entitytwo")
)
.build()
All works well, but if a new entity is coming inside the payload, the app won't show any data.
Example: an "entitythree" is added, to avoid the app stop showing info, I need to come and add
.withSubtype(EntityThree::class.java, "entitythree")
How can I avoid this behaviour, if the payload add new entities, nothing happen and the app will continue working well?
Thanks in advance
Upvotes: 2
Views: 1275
Reputation: 1463
Have a class denoting an unknown entity:
data class UnknownEntity : BaseClass {
val baseclass: String = "unknown"
}
Then, add to your factory:
PolymorphicJsonAdapterFactory
.of(BaseClass::class.java, "baseclass")
.withSubtype(EntityOne::class.java, "entityone")
.withSubtype(EntityTwo::class.java, "entitytwo")
.withDefaultValue(UnknownEntity())
Then in the rest of your logic, where you manipulate with the acquired entities, just ignore the UnknownEntity
instances, and the app should work as before.
Upvotes: 4