由于@alexander-egger的回答看起来有点过时,这里提供一个现代化的答案:
object ListAsMapDeserializer: KSerializer<Map<String, String>> {
private val mapSerializer = ListSerializer(MapEntrySerializer(String.serializer(), String.serializer()))
override val descriptor: SerialDescriptor = mapSerializer.descriptor
override fun deserialize(decoder: Decoder): Map<String, String> {
return mapSerializer.deserialize(decoder).associate { it.toPair() }
}
override fun serialize(encoder: Encoder, value: Map<String, String>) {
mapSerializer.serialize(encoder, value.entries.toList())
}
}
以及对其进行的测试:
@Test
fun listAsMap() {
val jsonElement = json.parseToJsonElement("{ \"map\": [ {\"key1\":\"value1\"}, {\"key2\":\"value2\"} ] }")
val testWithMap = json.decodeFromJsonElement<TestWithMap>(jsonElement)
assertEquals(mapOf("key1" to "value1", "key2" to "value2"), testWithMap.map)
}
@Test
fun mapAsList() {
val jsonElement = json.parseToJsonElement("{ \"map\": [ {\"key1\":\"value1\"}, {\"key2\":\"value2\"} ] }")
val testWithMap = TestWithMap(mapOf("key1" to "value1", "key2" to "value2"))
val serialized = json.encodeToJsonElement(TestWithMap.serializer(), testWithMap)
assertEquals(jsonElement, serialized)
}
@Serializable
data class TestWithMap(
@Serializable(with = ListAsMapDeserializer::class)
val map: Map<String, String>
)
{"someKey": "someValue", "otherKey": "otherValue"}
,这是更好的数据结构。 - MosiusList<Map<String,String>>
,作为客户端的内部步骤,然后再将其转换为所需的类型之一呢? - Laurence