eygraber
02/19/2021, 1:33 AMfun persist(foo: ???) {
Json.encodeToString(foo)
}
melatonina
02/19/2021, 12:11 PMclass ProjectId(value: UUID) : Id(value) {
companion object {
fun new() = ProjectId(newValue())
}
}
where Id
is
@Serializable
abstract class Id(
@Serializable(with = UUIDSerializer::class)
val value: UUID
) {
companion object {
fun newValue(): UUID = UUID.randomUUID()
}
override fun hashCode(): Int = value.hashCode()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Id) return false
if (!this.javaClass.isAssignableFrom(other.javaClass))
return false
return (value == other.value)
}
override fun toString(): String = "${javaClass.simpleName}($value)"
}
Is there a way to make all these Id
subclasses serializable without writing the serializers by hand?
Obviously, I'd like the various Id
subclasses to be inline
classes, but they would not be serializable at all.Ali Albaali
02/19/2021, 9:13 PM"""
[
{
// Posts
},
{
// Comments
}
]
"""
melatonina
02/22/2021, 11:20 AMthana
02/23/2021, 1:28 PM@Serializable sealed class SuperType
. Now we decided to add a method to all subtypes that basically create a copy from themselfs. Obvispously they are supposed to return their own type.
Hence e cahnged the declaration to @Serializable sealed class SuperType<T: SuperType<T>>
we can decalre the subtypes like class SubType: SuperType<SubType>{ override fun createCopy(): SubType = TODO() }
Unfortunately this seem to create a endless recursion in the compiler plugin generating the serializer for it. is this a known bug? is it a bug at all?nullium21
02/23/2021, 4:57 PM{
"type": "A",
"field": "foo"
}
and such for type B:
{
"type": "B",
"foo": "bar"
}
how to differentiate @Serializable
classes based on the type
field?
the classes I currently have are as follows:
@Serializable
sealed class Message {
@Serializable data class A(field: String, type: String): Message()
@Serializable data class B(foo: String, type: String): Message()
}
rocketraman
02/25/2021, 2:01 PMjson {
"foo" to "bar",
"baz" to json {
"gaz" to "gar"
}
}
Now it seems its a lot more verbose, with calls to put
. Was that intentional, or am I missing something?Kuba Petržílka
02/25/2021, 2:52 PMoverride fun deserialize(decoder: Decoder): NonEmptyString {
val decodedValue = decoder.decodeString()
when (val result = NonEmptyString.of(decodedValue)) {
is Success -> return result.value
is Failure -> throw SerializationException(
"Unable to deserialize '$decodedValue' of $FIELD_NAME into ${descriptor.serialName}: ${result.error.message}"
)
}
}
I need to see the context in the exception because there are many feilds of type NonEmptyString in the json document being deserializedDariusz Kuc
02/26/2021, 5:50 AMencodeDefaults = true
etc) globally?sindrenm
02/26/2021, 3:19 PMException
and parsing the message, which I'd rather not) to catch this error.melatonina
02/26/2021, 7:42 PM["folder",{"clipFolderId":{"value":"ae5cab51-4336-494f-86c8-e233cebc5467"}}]
instead of something like:
{type:"folder", "clipFolderId":{"value":"ae5cab51-4336-494f-86c8-e233cebc5467"}}
as is described in the documentation. I'm using org.jetbrains.kotlin:kotlin-serialization:1.4.31
and org.jetbrains.kotlinx:kotlinx-serialization-json:1.1.0
.
What could be the cause?Dariusz Kuc
02/28/2021, 2:06 AMkotlinx-serialization
wraps some json elements in "
making them strings?, i.e. given generic KSerializer
object AnyKSerializer : KSerializer<Any> {
override val descriptor: SerialDescriptor = buildClassSerialDescriptor("Any")
...
override fun deserialize(decoder: Decoder): Any {
val jsonDecoder = decoder as JsonDecoder
val element = jsonDecoder.decodeJsonElement() // why primitives are always strings?
return deserializeJsonElement(element)
}
private fun deserializeJsonElement(element: JsonElement): Any = when (element) {
is JsonObject -> {
element.mapValues { deserializeJsonElement(it.value) }
}
is JsonArray -> {
element.map { deserializeJsonElement(it) }
}
is JsonPrimitive -> element.content
}
}
and a simple data class
@Serializable
data class AnyMap(
val data: Map<String, @Serializable(with = AnyKSerializer::class) Any>
)
trying to deserialize
{
"data": {
"intVal": 123
}
}
but jsonDecoder.decodeJsonElement()
converts 123 int to "123" string
any ideas?Victor Ermolaev
03/02/2021, 8:25 AM@Serializable
processed?Matthew Cachia
03/02/2021, 4:45 PMEither<L, R>
(which means it contains either L
or R
) with the following logic:
override fun deserialize(decoder: Decoder): Either<L, R> =
try {
rightSerializer.deserialize(decoder).right()
} catch (e: Exception) {
leftSerializer.deserialize(decoder).left()
}
• If the given JSON payload is meant for type R
, everything works well.
• If the given JSON payload is meant for type L
, the exception is caught, however the cursor in the decoder has already progressed (and thus fails to deserialize)
Is there a way to reset the decoder back to its original cursor position? Am I approaching this the wrong way? Are there alternatives?
Thank you in advance.crumpf
03/02/2021, 8:24 PMencodeDefaults
in the Json serialization class so defaults do get encoded. But, this has the side effect of encoding null
into the json for properties that have been given default null values which is not desirable for communicating with some backend systems. So, I was wondering others have settled on for conventions or patterns to deal with this kind of thing. For example, lets considering the following example:
interface MyInterface {
val instruction: String
val requiredField: String
}
@Serializable
data class MyDataClass(
override val requiredField: String,
val optionalField: String? = null
) : MyInterface {
override val instruction: String = "doABarrelRoll"
}
Here, we’ve got MyInterface which describes the basic contract that all messages exchanged with a service should adopt. To see what the effects of encodeDefault
being true/false, the following code
val data = MyDataClass("foo")
println(Json.encodeToString(data))
println(Json { encodeDefaults = true }.encodeToString(data))
would output:
{"requiredField":"foo"}
{"requiredField":"foo","optionalField":null,"instruction":"doABarrelRoll"}
But, we desire:
{
"requiredField": "foo",
"instruction": "doABarrelRoll"
}
I know that a custom Serializer can be written for MyDataClass which could ignore encoding null values for properties. But, this seems that it would need to be done for all classes that incorporate optional properties. Apart from custom Serializers, has anyone used other strategies or structures for being able to encode defaults while ignoring nulls?gsala
03/03/2021, 1:07 PM@Serializable
data class Folder(
val content: SingleOrCollection<File>
)
@Serializable
data class File(val name: String)
@Serializable
sealed class SingleOrCollection<T> {
@Serializable
@SerialName("single")
class Single<T>(val data: T) : SingleOrCollection<T>()
@Serializable
@SerialName("collection")
class Collection<T>(val data: List<T>) : SingleOrCollection<T>()
}
I get a an exception when trying to serialize Folder(SingleOrCollection.Single(File(fileName)))
with json.encodeToString(folder)
kotlinx.serialization.SerializationException: Class 'File' is not registered for polymorphic serialization in the scope of 'Any'.
Mark the base class as 'sealed' or register the serializer explicitly.
It seems looks like a pretty simple use case. Does anyone know what the issue could be?Matthew Cachia
03/04/2021, 7:46 AM@Serializable
data class Request(
@Serializable(with = EitherSerializer::class)
val personOrCar: Either<Person, Car>,
@Serializable(with = EitherSerializer::class)
val catOrDog: Either<Cat, Dog>
)
I can easily specify my custom serializer to this sealed, third-party Either
class.
However,
@Serializable
data class Request(
//@Serializable(???)
val map: Map<String, Either<Cat, Dog>>
)
Besides some other ideas†, Is there a way I can specify a serializer for my entry value?
---
† one idea is to use a custom type to replace Map
and define its own custom serializer. But this is definitely not ideal.Nikolay Kasyanov
03/11/2021, 8:58 AMe: Compilation failed: Unbound symbols not allowed
with K/N after bumping kotlinx.serialization
to 1.1.0? Kotlin 1.4.31 is used, kotlinx.serialization
1.0.1 works fine.chao
03/15/2021, 12:18 AMbjonnh
03/18/2021, 7:52 PMdata class Vega(
val background: StringOrMoreComplex
)
v79
03/21/2021, 5:41 PMsubprojects { apply { plugin(...) } }
but that certainly doesn't work. I don't even know what the plugin ID is. NOTE: nothing to do with multiplatform/mobile/iOS; this is a libGDX game project.crummy
03/22/2021, 6:47 AMorg.jetbrains.kotlinx:kotlinx-serialization-runtime-js:$serialization_version
. But they seem to be using an older $serialization_version as me - I've got 1.1.0 but get "Could not find org.jetbrains.kotlinx:kotlinx-serialization-runtime-js:1.1.0".
Has this been replaced with another library or am I missing a repo?Karlo Lozovina
03/23/2021, 3:51 PMBoolean?
, and if the field is null, that's equivalent to it being false
. Is there a way to get rid of nulls, and encode them as the field being false?Dariusz Kuc
03/24/2021, 2:47 AMListSerializer
only accepts a single serializer - any idea whether it is possible to specify list of different serializers to be used?Jonathan Olsson
03/29/2021, 1:07 PMVikas Singh
03/29/2021, 7:47 PMadk
04/01/2021, 2:04 PMpambrose
04/01/2021, 5:59 PMrkeazor
04/03/2021, 3:19 PMmarzelwidmer
04/04/2021, 1:32 PMJSONN
Array
directly in my KMM
setup with `ktor`and KotlinxSerializer
and I don’t know how to define the Data
class 😞
Exception
kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 1: Expected '{, kind: CLASS'
JSON input: ["Albania","Argentina","Austral.....
at kotlinx.serialization.json.internal.JsonExceptionsKt.JsonDecodingException(JsonExceptions.kt:24)
at kotlinx.serialization.json.internal.JsonExceptionsKt.JsonDecodingException(JsonExceptions.kt:32)
Respnse
[
"Albania",
"Argentina",
"Australia",
...
]
Data class
@Serializable
data class CountryDto(
val names: ArrayList<String>?
)
API Call
suspend fun fetchAll() = client.get<List<CountryDto>>(baseUrl)
marzelwidmer
04/04/2021, 1:32 PMJSONN
Array
directly in my KMM
setup with `ktor`and KotlinxSerializer
and I don’t know how to define the Data
class 😞
Exception
kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 1: Expected '{, kind: CLASS'
JSON input: ["Albania","Argentina","Austral.....
at kotlinx.serialization.json.internal.JsonExceptionsKt.JsonDecodingException(JsonExceptions.kt:24)
at kotlinx.serialization.json.internal.JsonExceptionsKt.JsonDecodingException(JsonExceptions.kt:32)
Respnse
[
"Albania",
"Argentina",
"Australia",
...
]
Data class
@Serializable
data class CountryDto(
val names: ArrayList<String>?
)
API Call
suspend fun fetchAll() = client.get<List<CountryDto>>(baseUrl)
Javier
04/04/2021, 1:35 PMmarzelwidmer
04/04/2021, 1:38 PMOMG
and I was trying to fix it on my data class 🙂 it works … muchos gracias