benkuly
05/12/2022, 4:14 PMDeserializationStrategy
should be used depending on a field value.Yao-Wen Mei
05/13/2022, 4:27 AMformat de/encoder
[Link] works with a serializer
[Link].
I am following the Kotlin Serialization Guide, and I can see this encodeSerializableValue()
method is how de/encoder interact with serializer, but wandering if I can find more detail instructions or example guide. Thank you.
encoder.encodeSerializableValue(serializer, value)
kevin.cianfarini
05/13/2022, 2:26 PMJson.encodeToString(value: T)
. This is the following code snippet.
override var market: Market?
get() = marketJson?.let(json::decodeFromString)
set(value) { marketJson = value?.let(json::encodeToString) }
Is this a potential bug in K/N or serialization? Using Kotlin 1.6.10, serialization 1.3.1. Full stack trace in thread.Philip Dukhov
05/15/2022, 7:10 AM@Serializable
enum class ItemType {
@SerialName("0") Zero,
@SerialName("1") First,
}
But it fails with the following exception:
JsonDecodingException: Unexpected JSON token at offset 194: Expected quotation mark '"', but had '1' instead
JSON input: ....."type":1,.....
It doesn't seem to work because SerialName
is expecting a string and json has an int.
I can think of two ways to solve this:
1. Enabling lenient mode - I don't like this solution as it also removes restrictions from other fields, which I prefer to keep
2. Implementing a custom serializer - seems like too much of boilerplate code for such a simple task
Am I missing something?Sebastian Schuberth
05/16/2022, 3:39 PMtoString()
? Currently, I'm writing code like
@Serializer(File::class)
object FileSerializer : KSerializer<File> {
override fun serialize(encoder: Encoder, value: File) = encoder.encodeString(value.toString())
override fun deserialize(decoder: Decoder) = File(decoder.decodeString())
}
@Serializer(URI::class)
object URISerializer : KSerializer<URI> {
override fun serialize(encoder: Encoder, value: URI) = encoder.encodeString(value.toString())
override fun deserialize(decoder: Decoder) = URI(decoder.decodeString())
}
but this duplication seems rather dumb. Can I somehow generalize these serializers into one, and use that single serializer for both File
and URI
?Yao-Wen Mei
05/17/2022, 11:08 AM@Serializable
data class Project(val name:String, val owners: List<Users>)
@Serializable
data class Users(val name: String)
After serialization, I wish to get a nested map equals to:
val map = mutableMapOf<String, Any>()
map.put("name", "project_name")
map.put("owners", listOf(mapOf("name" to "user1"), mapOf("name" to "user2"))
Could you please give me some hint how can I implement this Encoder
please ( I do have a Decoder
working BTW)? Should my Encoder extend the AbstractEncoder()
or TaggedEncoder()
? May I get some document for how to implement this? The official guide only contains an example for serializing to List
, but does not show how to get the key values if I want to serialize to Map
. Thank you very much.Alejandro Moya
05/17/2022, 6:07 PMString
, an Integer
or a Boolean
, is there a way to achieve that behaviour with serialization?ribesg
05/18/2022, 10:01 AM@Serializable
data class Event(
val id: String,
val date: Date = Date.now(),
)
@Test
fun test() {
repeat(100) {
println(Json.encodeToString(Event("Test")))
}
}
…
{"id":"Test"}
{"id":"Test"}
{"id":"Test","date":"2022-05-18T10:00:47.011Z"}
{"id":"Test"}
{"id":"Test"}
{"id":"Test"}
…
Ovsyannikov Alexey
05/18/2022, 10:05 AMzt
05/19/2022, 7:50 PM[ { "somekey": { } }, { "someotherkey": { } } ]
I wanna be able to check the name of the first key in the object and then serialize to a specific class depending on what it isSlackbot
05/20/2022, 10:31 PMMatthew Olsson
05/21/2022, 2:12 AM["Bob", 24]
into class Person(val name: String, val age: Int)
. Assuming of course that I already know the array corresponds to the Person
class (in reality, my data looks more like { "person": ["Bob", 24] }
Jan
05/22/2022, 10:26 AMPedro Henrique
05/22/2022, 7:47 PMkotlinx.serialization.cbor.internal.CborDecodingException: Expected start of string, but found 50
error. The byte array data seems to be the same as the original one in Rust when converting them to a hexadecimal format. I can deserialize normally the same data on Rust through the cbor4ii
library. I also tried using another library (cborium
) and I still get the same error in the Kotlin side.Václav Škorpil
05/23/2022, 9:48 AM<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="<http://schemas.xmlsoap.org/soap/envelope/>" xmlns="<http://www.pds.eu/vOKO/v0200>" xmlns:eph="<http://www.ccv.cz/EPH_GCP01G>">
<soapenv:Body>
<Request vOKOid="EPH_GCP01G">
<RequestContent>
<eph:REQUEST>
<eph:GETDATA>1</eph:GETDATA>
<eph:IDLAST>22</eph:IDLAST>
</eph:REQUEST>
</RequestContent>
</Request>
</soapenv:Body>
</soapenv:Envelope>
As you can see, there are more than one namespace in the envelope.I xmlutil is only @XmlSerialName which can specify only one namespace. How should i handle this?jean
05/23/2022, 1:06 PMinterface DeviceAttribute<T> {
val name: String
val value: T
}
@SharedImmutable
internal val module = SerializersModule {
polymorphic(baseClass = DeviceAttribute::class, baseSerializer = null) {
subclass(AlarmEntryDevice::class)
default { Unknown.serializer() }
}
}
@Serializable
data class Device(
val id: String,
val name: String,
val icon: String,
val iconOptions: List<String>,
val attributes: List<DeviceAttribute<*>> = emptyList(),
val profiles: List<ActiveProfileMode>?,
)
But I get this error Serializer has not been found for type 'Any?'. To use context serializer as fallback, explicitly annotate type or property with @Contextual
Adding the annotation doesn’t change anything though. What should I do?jean
05/23/2022, 8:54 PMSerializersModule
to look for an attribute called name
instead of type
without registering a custom serializer?Igor Kolomiets
05/25/2022, 2:53 PM@Serializable
data class Category(val id: String, val children: Set<Category> = emptySet())
For the sake of having “stable” diff of the updated JSON file, I’d like to enforce order of the children
Set’s elements based on lexicographic order of the element’s id
field.
The solution I was able to come up with is to use custom serializer based on `JsonTransformingSerializer`:
object CategorySetSerializer : JsonTransformingSerializer<Set<Category>>(SetSerializer(Category.serializer())) {
override fun transformSerialize(element: JsonElement) = super.transformSerialize(
if (element is JsonArray)
JsonArray(element.sortedBy { it.jsonObject["id"]?.jsonPrimitive?.content })
else
element
)
}
@Serializable
data class Category(
val id: String,
@Serializable(with = CategorySetSerializer::class)
val children: Set<Category> = emptySet()
)
Unfortunately, this solution seems too low level, brittle and JSON specific.
What can be other approaches to enforce particular ordering of serialized Set’s elements?
Ideally, I’d like to pass in the @Serializable
my custom comparator when specific Set’s elements ordering is required.nikolaymetchev
05/26/2022, 11:45 AMJsonObject
? If I have such an object already and I wish to add a couple of elements somewhere nested deep inside is that possible programatically? I think I would have to effectively clone the whole thing myself in order to achieve that.Yao-Wen Mei
05/26/2022, 6:00 PM@SerialInfo
@Target{
AnnotationTarget.PROPERTY_SETTER,
AnnotationTarget.PROPERTY_GETTER}
annotation class KDocumentId
data class File( @get: KDocumentId val name:String?= null)
// this will just return empty list []
descriptor.getElementAnnotations(elementIndex)
Tomas Kormanak
05/27/2022, 1:46 PM@Serializable
but I would like to use different serializer than default one but I can't change the library code.zt
05/28/2022, 1:15 PMcompanion object Serializer : JsonContentPolymorphicSerializer<Renderer>(Renderer::class) {
override fun selectDeserializer(element: JsonElement) = when {
"slimVideoMetadataSectionRenderer" in element.jsonObject -> SlimVideoMetadataSectionRenderer.serializer()
"itemSectionRenderer" in element.jsonObject -> RelatedItemsRenderer.serializer()
"shelfRenderer" in element.jsonObject -> ShelfRenderer.serializer()
else -> throw NoWhenBranchMatchedException()
}
}
though how would I make it serialize using the object inside of the key?jean
05/31/2022, 2:02 PMPolymorphic serializer was not found for class discriminator 'batteryPercentage', JSON input: {"name":"batteryPercentage","value":70}
@JsonClassDiscriminator("name")
interface DeviceAttribute
@Serializable
data class Device(
val id: String,
val name: String,
val icon: String,
val iconOptions: List<String>,
val attributes: List<DeviceAttribute> = emptyList(),
val profiles: List<ActiveProfileMode>?,
)
@Serializable
@SerialName("batteryPercentage")
data class BatteryPercentage(val value: Int) : DeviceAttribute
What am I missing here?Jan
06/01/2022, 6:21 PMkotlinforandroid
06/02/2022, 8:02 PMDJ
06/04/2022, 1:05 AM$schema
key at the top level. I am parsing it into a Map<String, Def>
(Def is a class I have defined), so when the string value in the $schema
key is encountered, it throws an exception. I simply want to ignore the value of the $scheam
key, what is the best way to do this?kotlinforandroid
06/04/2022, 6:32 AMIndexOutOfBoundsException
and I do not really get why. (thread)Adam S
06/04/2022, 11:30 AM@Serializable
, on the field, for a whole file, in multiple ways with a SerializersModules, and there's also reflection.
Is the order of priority defined somewhere?
I'm asking because I want to see how to override a serializer that's defined on a class with @Serializable(with = ...)
, and it's not clear in which order serializers are considered and selected.Katyrin Roman
06/08/2022, 6:20 AMankushg
06/10/2022, 6:12 PMmain
branch, but we have a branch where we’ve made a couple structural changes (with absolutely no new @Serializable
classes) and things are just breaking for mysterious reasons 😞
Has anyone else here experienced it? Any ways to narrow down the cause?