jackson-module-kotlin
jackson-module-kotlin copied to clipboard
Using delegated properties in deserialization
Your question We would like to make use of kotlins 'inheritance by delegation' feature. In the json-structure the object should be flat, i.e. not exposing the delegation. Suppressing the delegation during serialization works, but deserialization fails. Is there a way to achive this or should we raise a feature request?
Example:
class DelegateTest {
interface SharedInterface {
val commonString: String
}
data class InternalSharedDelegate(override val commonString: String) : SharedInterface
data class ExposedObject(
// ignore/hide the delegation in json serialization
@param:JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
val delegate: InternalSharedDelegate,
val otherValue: String
) : SharedInterface by delegate
private val objectMapper = jsonMapper { addModule(kotlinModule()) }
@Test
fun `should deserialize delegated property`() {
val exposedObject = ExposedObject(delegate = InternalSharedDelegate("a"), otherValue = "b")
val serialized = objectMapper.writeValueAsString(exposedObject)
assertEquals("{\"otherValue\":\"b\",\"commonString\":\"a\"}", serialized)
// following line causes:
// Instantiation of [simple type, class DelegateTest$ExposedObject] value failed for JSON property delegate due to missing (therefore NULL) value for creator parameter delegate which is a non-nullable type
val deserialized: ExposedObject = objectMapper.readValue(serialized)
assertEquals(exposedObject, deserialized)
}
}