louiscad
10/12/2022, 1:13 AM@OptIn(ExperimentalSerializationApi::class)
@Serializable
data class GenericWrapper<T>(
@ProtoNumber(1) val name: String,
@ProtoNumber(2) val content: T,
)
Brent Beardsley
10/12/2022, 11:31 PM@kotlinx.serialization.Serializable
data class Geolocation(
val latitude: Double,
val longitude: Double
)
that I'm using to get responses from rest calls. Unfortunately the rest api is not consistent and so in some places I need to use lat
and lng
instead of latitude
and longitude
. What is the best way to handle this? A custom serializer or extend the class and add @SerialName
if that's possible? I'd like to really just have one Geolocation
so I'm leaning towards the custom serializer...zt
10/13/2022, 4:12 AM@Serializable
data class ReplyParams(
@ProtoNumber(2) val videoId: String,
@ProtoNumber(4) val commentId: String
) {
@ProtoNumber(5)
private val unknownParams: UnknownParams = UnknownParams()
@ProtoNumber(10)
private val unknownNumber: Int = 0
@Serializable
private class UnknownParams {
@ProtoNumber(1)
private val unknownNumber: Int = 7
}
}
xxfast
10/13/2022, 4:37 AMtype
field to something else? to achieve something like
{
"typeKey": "owned",
"status": "open",
"name": "kotlinx.coroutines",
"owner": "kotlin"
}
igor.wojda
10/13/2022, 2:11 PM{
"album": {
"artist": "Michael Jackson",
"tags": {
"tag": [
{
"url": "https://www.last.fm/tag/pop",
"name": "pop"
},
{
"url": "https://www.last.fm/tag/soul",
"name": "soul"
}
]
}
}
}
The tags
attribute contains a single child tag
, so some kind of container (TrackContainer
) class is required to parse this JSON:
@Serializable
internal data class AlbumApiModel(
@SerialName("artist") val artist: String,
@SerialName("tracks") val tracks: TrackContainer? = null,
)
@Serializable
internal data class TrackContainer(
@SerialName("track") val track: List<AlbumTrackApiModel>,
)
Since creation of this class is a bit verbose I wonder if there is a way to parse nested attributes without a need to define TrackContainer
class- something like @SerialName("tracks.track")
@Serializable
internal data class AlbumApiModel(
@SerialName("artist") val artist: String,
@SerialName("tracks.track") val tracks: List<Track>? = null,
)
zt
10/16/2022, 4:16 AM{
"contents": {
"singleColumnBrowseResultsRenderer": {
"tabs": [
{
"tabRenderer": {
"content": {
"sectionListRenderer": {
"contents": [
{
"playlistVideoListRenderer": { ... }
}
]
}
}
}
}
]
}
}
}
{
"contents": {
"singleColumnBrowseResultsRenderer": {
"tabs": [
{
"tabRenderer": {
"content": {
"sectionListRenderer": {
"contents": [
{
"itemSectionRenderer": { ... }
}
]
}
}
}
}
]
}
}
}
gts13
10/16/2022, 3:16 PM@Serializable
data class Accounts(
val data: List<Account>
) {
@Serializable
data class Account(
@SerialName("name")
val name: String,
@SerialName("lastname")
val lastname: String,
)
}
The Json.encodeToString()
and decodeToString
returns a JsonObject
{
"data": [
{
"name": "Mike",
"lastname": "Ekim"
},
{
"name": "John",
"lastname": "Nhoj"
},
...
How can encode the data class to return a JsonArray? Like the following:
data: [{
"name": "Mike",
"lastname": "Ekim"
}, {
"name": "John",
"lastname": "Nhoj"
},
...]
Jan Skrasek
10/17/2022, 12:07 PMMichal Fudala
10/17/2022, 1:08 PMprivate inline fun <reified K, reified V> JsonElement.decodeOne(key: String): Map<K, V> {
return jsonObject[key]
?.let { Json.decodeFromJsonElement<Map<K, V>>(it) }
.orEmpty()
}
private fun <K, V> JsonElement.decodeOne(key: String): Map<K, V> {
return jsonObject[key]
?.let { Json.decodeFromJsonElement<Map<K, V>>(it) }
.orEmpty()
}
but only the first one works at runtime.
Wouldn't it be possible to check this at compile time. The same way it's done (screenshot) for Json.decodeFromJsonElement<K>(smth)
when K
is generic, but not reified.
Or is type-erasure still a problem here?Achraf Amil
10/17/2022, 3:03 PMPLUGIN_IS_NOT_ENABLED
warning is only shown on IDE and doesn’t log (or fail when allWarningsAsErrors
) ?Settingdust
10/18/2022, 7:23 AMencoder.encodeSerializableValue(serializers[0]!!(), value)
will error with type mismatch. Expected CapturedType(out X*>)
but X`<*>`. How to pass the value?
// An external class from lib
class X<T>
object XSerializer : KSerializer<X<Int>> {
override val descriptor: SerialDescriptor
get() = TODO("Not yet implemented")
override fun deserialize(decoder: Decoder): X<Int> {
TODO("Not yet implemented")
}
override fun serialize(encoder: Encoder, value: X<Int>) {
TODO("Not yet implemented")
}
}
// A map to take correct serializer by arg
val serializers: Map<Int, () -> KSerializer<out X<*>>> = mapOf(0 to { XSerializer })
object GenericSerializer : KSerializer<X<*>> {
override val descriptor: SerialDescriptor
get() = TODO("Not yet implemented")
override fun deserialize(decoder: Decoder): X<*> {
TODO("Not yet implemented")
}
override fun serialize(encoder: Encoder, value: X<*>) {
encoder.encodeSerializableValue(serializers[0]!!(), value)
}
}
There is a link testable. https://pl.kotl.in/VVNMv8ZsoAnton Wiblishauser
10/18/2022, 5:07 PMSettingdust
10/22/2022, 1:12 PMclass A : Map<String, A>
. The map is guava multimap that not implement the map interface. But can be converted to a map.
Below is what I tried. Will throw StackOverflowError
from SetSerializer
object Serializer : KSerializer<A> {
private val serializer by lazy { MapSerializer(String.serializer(), SetSerializer(this)) }
override val descriptor by lazy {
SerialDescriptor(
"A",
serializer.descriptor
)
}
override fun deserialize(decoder: Decoder) =
A(Multimaps.newMultimap(serializer.deserialize(decoder)) { setOf() })
override fun serialize(encoder: Encoder, value: A) =
serializer.serialize(encoder, value.asMap().mapValues { it.value.toSet() })
}
christophsturm
10/23/2022, 1:01 PMkxser
seems to be used by some libs but imo thats not very catchy. kotlinxserialization
is hard to read. can anyone think of something nicer?Alex Mihailov
10/24/2022, 8:35 AMgradlew clean build
:
\projects\kotlinx.serialization\core\jvmMainModule\src\module-info.java:4: error: package is empty or does not exist: kotlinx.serialization
exports kotlinx.serialization;
^
JDK liberica 11.0.16, language level 11.
When rebuild project, the error does not reproduce.
Has anyone encountered this problem and knows the solution?Mohit Sharma
10/25/2022, 8:05 PMCaused by: kotlinx.serialization.json.internal.JsonDecodingException: Polymorphic serializer was not found for missing class discriminator ('null')
2022-10-25 20:31:56.910 4548-4548/com.socialpillars.ngo E/AndroidRuntime: JSON input: .....te_time":"2022-03-30T06:43:29.433318+05:30","type":"post"}]}
data class Posts(
@SerialName("uuid") val postId: String,
@SerialName("description") val description: String,
@SerialName("likes_count") var likesCount: Int,
@SerialName("images") private val _images: List<Image>,
@SerialName("user") val user: User,
@SerialName("is_liked") var isLiked: Boolean,
@SerialName("create_time") private val _eventStartTime: String,
var isMyPost: Boolean = false
)
data class FeedItem(
@SerialName("post") var posts: Posts?,
@SerialName("event") var events: Events?,
@SerialName("type") var type: FeedType
)
zt
10/26/2022, 2:06 AM@Serializable
open class Test<T>(
val test: T
)
@Serializable
class TestImpl : Test<String>()
// This doesn't work cause it needs the parameter
Assaf Shouval
10/26/2022, 7:22 AMLandry Norris
10/26/2022, 5:19 PMEmil Kantis
10/26/2022, 8:29 PMLocalDateTime
, Instant
, UUID
, URL
, but also have multiplatform support for serializing enums by their ordinal value.Christian Würthenr
10/28/2022, 5:35 AM{"actual":"","target":null}
but both values are supposed to be Float?
. I already use coerceInputValues
to allow string values to be parsed but the ""
doesn’t get translated to null
or something.
Is there a way I can tell Kotlin to use the default value if it can’t deserialize something?zt
10/29/2022, 5:48 AMExpected JsonPrimitive at text, found {"runs":[{"text":"All"}]}
I'm not sure what I'm doing wrong here
internal typealias ApiText = @Serializable(ApiTextSerializer::class) String
private class ApiTextSerializer : KSerializer<String> {
override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ApiText")
override fun deserialize(decoder: Decoder): String {
val input = decoder as JsonDecoder
return input.decodeJsonElement().jsonObject["runs"]!!.jsonArray.joinToString(separator = "") {
it.jsonObject["text"]!!.jsonPrimitive.content
}
}
override fun serialize(encoder: Encoder, value: String) {
throw RuntimeException("Serialization is not needed")
}
}
Assaf Shouval
10/30/2022, 6:00 PMobject BigIntegerSerializerForMeta :
KSerializer<BigInteger> {
override val descriptor: SerialDescriptor = buildClassSerialDescriptor("BigIntSerializer") {
element("value", PolymorphicPrimitiveSerializer(String.serializer()).descriptor)
}
const val radix = 16
override fun deserialize(decoder: Decoder): BigInteger {
return BigInteger(decoder.decodeSerializableValue(String.serializer()), radix)
}
override fun serialize(encoder: Encoder, value: BigInteger) =
encoder.encodeSerializableValue(String.serializer(), value.toString(radix))
}
I get {"1234567890"} instead of {"type":BigIntSerializer,"value":"1234567890"}Erik
10/31/2022, 8:39 AMfalse
by default? Is it because serializing a map to an array is non-standard behaviour? And throwing an exception (if false
) is standard behaviour?Sunil Kumar
11/01/2022, 2:43 PMCaused by: kotlinx.serialization.json.internal.JsonDecodingException: Polymorphic serializer was not found for missing class discriminator ('null')
Not able to find any solution for that. Can anyone help me with that. Tried some solutions from google and stackoverflow, but didnt worked.Assaf Shouval
11/02/2022, 2:35 PMval module = SerializersModule {
polymorphic(Any::class) {
subclass(Int::class, PolymorphicPrimitiveSerializer(Int.serializer()))
subclass(String::class, PolymorphicPrimitiveSerializer(String.serializer()))
subclass(Pair::class, PolymorphicSerializer(Pair::class))
}
polymorphic(Pair::class) {
PairSerializer(Int.serializer(), String.serializer())
}
}
val format = Json { serializersModule = module }
val mm = mapOf<String, Any>()
.plus("intString pair" to 5 to "FIVE")
How to declare the Serialization for the Pair?Emil Kantis
11/03/2022, 11:02 PMPrimitiveSerialDescriptor
. The docs state:
For primitive serialization, the PrimitiveSerialDescriptor function must be used with a unique name of the type that is being serialized.But this KDoc example sets the name to
kotlinx.serialization.LongAsStringSerializer
, which is the name of the serializer, not the type being serialized. Which one is correct?elect
11/04/2022, 9:09 AM<?xml version="1.0" encoding="UTF-8"?>
<registry>
<comment>
Copyright 2015-2022 The Khronos Group Inc.
SPDX-License-Identifier: Apache-2.0 OR MIT
</comment>
I started with
fun parse(text: String) {
val format = XML {}
val registry = format.decodeFromString<Registry>(text)
}
@Serializable
data class Registry(
val comment: String,)
but I get:
Execution failed for task ':generateCode'.
> Could not find a field for name (vkk.Registry) Registry/comment (Element)
candidates: Comment at position Line number = 3What am I missing?
George
11/04/2022, 10:39 AM@file:UseSerializers(UrlSerializer::class)
// using serializer explicitly works
val url = URL("<https://test>")
val protobytes = ProtoBuf.encodeToByteArray(UrlSerializer, url)
val result = ProtoBuf.decodeFromByteArray(UrlSerializer, protobytes)
// use file serializer, this fails
shouldThrow<SerializationException> {
val protobytes2 = ProtoBuf.encodeToByteArray(url)
val result2: URL = ProtoBuf.decodeFromByteArray(protobytes)
println(result2)
}
// use typealias serializer, this also fails
shouldThrow<SerializationException> {
val url2: UrlAsString = url
val protobytes2 = ProtoBuf.encodeToByteArray(url)
val result2: UrlAsString = ProtoBuf.decodeFromByteArray(protobytes)
println(result2)
}
// using inside data class works (like in the guide)
@Serializable
data class TestUrl(val value: URL)
val testUrl = TestUrl(url)
val proto = ProtoBuf.encodeToByteArray(testUrl)
val resultUrl: TestUrl = ProtoBuf.decodeFromByteArray(proto)
println(resultUrl)
In case, when using file serializer or global how come it throws: cannot find serializer for URL ?IsaacMart
11/04/2022, 3:53 PMIsaacMart
11/04/2022, 3:53 PM