Is there a way of deserializing json using
sealed class Layer
data class ShapeLayer(var type: LayerType) : Layer
data class TextLayer(var type: LayerType) : Layer
data class ImageLayer(var type: LayerType) : Layer
LayerType is just some enum which can be used to distinguish which type should this object have.
I thought I could add Adapter this way:
class LayerAdapter{
@FromJson
fun fromJson(layerJson: LayerJson): Layer {
return when (layerJson.layerType) {
LayerType.SHAPE -> PreCompLayer()
LayerType.SOLID -> SolidLayer()
LayerType.Text -> TextLayer()
}
}
}
Where LayerJson would be object which has every possible field of all LayerTypes.
Now the problem is:
Cannot serialize abstract class com.example.models.layers.Layer
I could try to use interface, but I don't think it would be correct to use empty interface in this.
It turned out that my code was actually correct from beginning!
Problem was with field declaration inside data Class:
It works with val, and doesn't work with var! Kotlin somehow creates different code down below. This is my final code for this part of model:
Yes, you can create a custom type adapter to parse json according to the
layerType
like this:Here I have make some changes to your data class for clarity (an extra property to each of the
Layer
type, e.g.shape
forShapeLayer
):Testing code:
Output:
Edit: You can add the adapter as usual when you are trying to parse other object which contain
Layer
. Suppose you have an object like this:Testing code: