1 /* 2 * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. 3 */ 4 5 package kotlinx.serialization.internal 6 7 import kotlinx.serialization.* 8 import kotlinx.serialization.descriptors.* 9 import kotlinx.serialization.encoding.* 10 11 /** 12 * Serializer for Kotlin's singletons (denoted by `object` keyword). 13 * To preserve singleton identity after serialization and deserialization, object serializer 14 * uses an [object instance][objectInstance]. 15 * By default, a singleton is serialized as an empty structure, e.g. `{}` in JSON. 16 */ 17 @PublishedApi 18 @OptIn(ExperimentalSerializationApi::class) 19 internal class ObjectSerializer<T : Any>(serialName: String, private val objectInstance: T) : KSerializer<T> { 20 21 @PublishedApi // See comment in SealedClassSerializer 22 internal constructor( 23 serialName: String, 24 objectInstance: T, 25 classAnnotations: Array<Annotation> 26 ) : this(serialName, objectInstance) { 27 _annotations = classAnnotations.asList() 28 } 29 30 private var _annotations: List<Annotation> = emptyList() 31 <lambda>null32 override val descriptor: SerialDescriptor by lazy(LazyThreadSafetyMode.PUBLICATION) { 33 buildSerialDescriptor(serialName, StructureKind.OBJECT) { 34 annotations = _annotations 35 } 36 } 37 serializenull38 override fun serialize(encoder: Encoder, value: T) { 39 encoder.beginStructure(descriptor).endStructure(descriptor) 40 } 41 deserializenull42 override fun deserialize(decoder: Decoder): T { 43 decoder.decodeStructure(descriptor) { 44 if (decodeSequentially()) 45 return@decodeStructure 46 47 when (val index = decodeElementIndex(descriptor)) { 48 CompositeDecoder.DECODE_DONE -> { 49 return@decodeStructure 50 } 51 else -> throw SerializationException("Unexpected index $index") 52 } 53 } 54 return objectInstance 55 } 56 } 57