deserialize

open override fun deserialize(decoder: Decoder): T(source)

Deserializes the value of type T using the format that is represented by the given decoder. deserialize method is format-agnostic and operates with a high-level structured Decoder API. As long as most of the formats imply an arbitrary order of properties, deserializer should be able to decode these properties in an arbitrary order and in a format-agnostic way. For that purposes, CompositeDecoder.decodeElementIndex-based loop is used: decoder firstly signals property at which index it is ready to decode and then expects caller to decode property with the given index.

Throws SerializationException if value cannot be deserialized.

Example of deserialize method:

class MyData(int: Int, stringList: List<String>, alwaysZero: Long)

fun deserialize(decoder: Decoder): MyData = decoder.decodeStructure(descriptor) {
// decodeStructure decodes beginning and end of the structure
var int: Int? = null
var list: List<String>? = null
loop@ while (true) {
when (val index = decodeElementIndex(descriptor)) {
DECODE_DONE -> break@loop
0 -> {
// Decode 'int' property as Int
int = decodeIntElement(descriptor, index = 0)
}
1 -> {
// Decode 'stringList' property as List<String>
list = decodeSerializableElement(descriptor, index = 1, serializer<List<String>>())
}
else -> throw SerializationException("Unexpected index $index")
}
}
if (int == null || list == null) throwMissingFieldException()
// Always use 0 as a value for alwaysZero property because we decided to do so.
return MyData(int, list, alwaysZero = 0L)
}

See also

for additional information about general contracts and exception specifics

Throws

if non-optional fields were not found during deserialization

in case of any deserialization-specific error

if the decoded input is not a valid instance of T