Deactivated User
10/30/2020, 12:02 PMpeekandpoke
10/30/2020, 12:05 PMval type: KType = ...
val result = Json.decodeFromString(ktype, string)
Does this functionality exist?
Or asked the other way around: Is there something like a serializer-registry, that will give me the serializer for a given KClass or KType?
Thanks!Christian Maier
10/30/2020, 4:49 PMGilles Barbier
10/30/2020, 5:12 PMTomasz Krakowiak
11/02/2020, 4:07 PM@Serializable
sealed class A(
val foo: String
) {
@Serializable
class B(
foo: String,
val bar: String,
) : A(foo)
}
Getting error "This class is not serializable automatically because it has primary constructor parameters that are not properties"Tomasz Krakowiak
11/02/2020, 6:07 PMorg.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: Failed to generate expression: KtNameReferenceExpression
File being compiled: (40,39) in D:/work/workspace/boardgames/games/turingresistance/src/commonMain/kotlin/house/boardgames/games/turingresistance/model/deck/store/CardStore.kt
The root cause java.lang.UnsupportedOperationException was thrown at: org.jetbrains.kotlin.codegen.context.CodegenContext.getOuterExpression(CodegenContext.java:222)
at org.jetbrains.kotlin.codegen.ExpressionCodegen.genQualified(ExpressionCodegen.java:335)
at org.jetbrains.kotlin.codegen.ExpressionCodegen.genQualified(ExpressionCodegen.java:293)
at org.jetbrains.kotlin.codegen.ExpressionCodegen.gen(ExpressionCodegen.java:414)
at org.jetbrains.kotlin.codegen.ExpressionCodegen.gen(ExpressionCodegen.java:422)
at org.jetbrains.kotlin.codegen.ExpressionCodegen.gen(ExpressionCodegen.java:418)
at org.jetbrains.kotlinx.serialization.compiler.backend.jvm.SerializableCodegenImpl.genInitProperty(SerializableCodegenImpl.kt:279)
at org.jetbrains.kotlinx.serialization.compiler.backend.jvm.SerializableCodegenImpl.doGenerateConstructorImpl(SerializableCodegenImpl.kt:218)
at org.jetbrains.kotlinx.serialization.compiler.backend.jvm.SerializableCodegenImpl.access$doGenerateConstructorImpl(SerializableCodegenImpl.kt:38)
at org.jetbrains.kotlinx.serialization.compiler.backend.jvm.SerializableCodegenImpl$generateInternalConstructor$1.invoke(SerializableCodegenImpl.kt:81)
at org.jetbrains.kotlinx.serialization.compiler.backend.jvm.SerializableCodegenImpl$generateInternalConstructor$1.invoke(SerializableCodegenImpl.kt:38)
at org.jetbrains.kotlinx.serialization.compiler.backend.jvm.JVMCodegenUtilKt$generateMethod$1.doGenerateBody(JVMCodegenUtil.kt:141)
at org.jetbrains.kotlin.codegen.FunctionGenerationStrategy$CodegenBased.generateBody(FunctionGenerationStrategy.java:86)
at org.jetbrains.kotlin.codegen.FunctionCodegen.generateMethodBody(FunctionCodegen.java:648)
at org.jetbrains.kotlin.codegen.FunctionCodegen.generateMethodBody(FunctionCodegen.java:483)
at org.jetbrains.kotlin.codegen.FunctionCodegen.generateMethod(FunctionCodegen.java:259)
at org.jetbrains.kotlin.codegen.FunctionCodegen.generateMethod(FunctionCodegen.java:164)
at org.jetbrains.kotlinx.serialization.compiler.backend.jvm.JVMCodegenUtilKt.generateMethod(JVMCodegenUtil.kt:138)
at org.jetbrains.kotlinx.serialization.compiler.backend.jvm.SerializableCodegenImpl.generateInternalConstructor(SerializableCodegenImpl.kt:81)
at org.jetbrains.kotlinx.serialization.compiler.backend.common.SerializableCodegen.generateSyntheticInternalConstructor(SerializableCodegen.kt:41)
at org.jetbrains.kotlinx.serialization.compiler.backend.common.SerializableCodegen.generate(SerializableCodegen.kt:33)
at org.jetbrains.kotlinx.serialization.compiler.backend.jvm.SerializableCodegenImpl$Companion.generateSerializableExtensions(SerializableCodegenImpl.kt:48)
at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationCodegenExtension.generateClassSyntheticParts(SerializationCodegenExtension.kt:29)
at org.jetbrains.kotlin.codegen.ImplementationBodyCodegen.generateSyntheticPartsAfterBody(ImplementationBodyCodegen.java:440)
at org.jetbrains.kotlin.codegen.MemberCodegen.generate(MemberCodegen.java:132)
at org.jetbrains.kotlin.codegen.MemberCodegen.genClassOrObject(MemberCodegen.java:302)
at org.jetbrains.kotlin.codegen.MemberCodegen.genClassOrObject(MemberCodegen.java:286)
at org.jetbrains.kotlin.codegen.MemberCodegen.genClassOrObject(MemberCodegen.java:312)
at org.jetbrains.kotlin.codegen.ClassBodyCodegen.generateDeclaration(ClassBodyCodegen.java:176)
at org.jetbrains.kotlin.codegen.ClassBodyCodegen.generateBody(ClassBodyCodegen.java:80)
at org.jetbrains.kotlin.codegen.MemberCodegen.generate(MemberCodegen.java:129)
at org.jetbrains.kotlin.codegen.MemberCodegen.genClassOrObject(MemberCodegen.java:302)
at org.jetbrains.kotlin.codegen.MemberCodegen.genClassOrObject(MemberCodegen.java:286)
at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generateClassesAndObjectsInFile(PackageCodegenImpl.java:119)
at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generateFile(PackageCodegenImpl.java:138)
at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generate(PackageCodegenImpl.java:70)
at org.jetbrains.kotlin.codegen.DefaultCodegenFactory.generatePackage(CodegenFactory.kt:88)
at org.jetbrains.kotlin.codegen.DefaultCodegenFactory.generateModule(CodegenFactory.kt:67)
at org.jetbrains.kotlin.codegen.KotlinCodegenFacade.compileCorrectFiles(KotlinCodegenFacade.java:35)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.generate(KotlinToJVMBytecodeCompiler.kt:647)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:210)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli$default(KotlinToJVMBytecodeCompiler.kt:162)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:169)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:52)
at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:88)
at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:44)
at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:98)
at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:371)
at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:105)
at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compileIncrementally(IncrementalCompilerRunner.kt:249)
at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.access$compileIncrementally(IncrementalCompilerRunner.kt:38)
at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner$compile$2.invoke(IncrementalCompilerRunner.kt:80)
at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compile(IncrementalCompilerRunner.kt:92)
at org.jetbrains.kotlin.daemon.CompileServiceImplBase.execIncrementalCompiler(CompileServiceImpl.kt:602)
at org.jetbrains.kotlin.daemon.CompileServiceImplBase.access$execIncrementalCompiler(CompileServiceImpl.kt:93)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:1644)
at jdk.internal.reflect.GeneratedMethodAccessor98.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at java.rmi/sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:359)
at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:200)
at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:691)
at java.rmi/sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:587)
at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:828)
at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:705)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:704)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: java.lang.UnsupportedOperationException: Don't know how to generate outer expression: Class: class WordCardStore
at org.jetbrains.kotlin.codegen.context.CodegenContext.getOuterExpression(CodegenContext.java:222)
at org.jetbrains.kotlin.codegen.context.CodegenContext.lookupInContext(CodegenContext.java:563)
at org.jetbrains.kotlin.codegen.context.MethodContext.lookupInContext(MethodContext.java:83)
at org.jetbrains.kotlin.codegen.ExpressionCodegen.findCapturedValue(ExpressionCodegen.java:2115)
at org.jetbrains.kotlin.codegen.ExpressionCodegen.findLocalOrCapturedValue(ExpressionCodegen.java:2106)
at org.jetbrains.kotlin.codegen.ExpressionCodegen.generateNonIntrinsicSimpleNameExpression(ExpressionCodegen.java:1986)
at org.jetbrains.kotlin.codegen.ExpressionCodegen.visitSimpleNameExpression(ExpressionCodegen.java:1913)
at org.jetbrains.kotlin.codegen.ExpressionCodegen.visitSimpleNameExpression(ExpressionCodegen.java:114)
at org.jetbrains.kotlin.psi.KtNameReferenceExpression.accept(KtNameReferenceExpression.kt:59)
at org.jetbrains.kotlin.codegen.ExpressionCodegen.genQualified(ExpressionCodegen.java:311)
... 70 more
Davide Giuseppe Farella
11/03/2020, 8:33 AMtype
, we implemented the model with `sealed class`; serialization works flawlessly, but deserialization doesn’t include the field type
. What is the best way to deal with it? We’re on 1.4.10Antoine Gagnon
11/03/2020, 6:05 PManimalType
field isn’t serialized in my code:
@Serializable
abstract class Animal{
abstract val name : String
abstract val animalType : String
}
@Serializable
class Dog(override val name:String):Animal(){
override val animalType: String = "Dog"
}
val rex = Dog("Rex")
val string = Json.encodeToString(Dog.serializer(),rex)
println(string)
The string
value at the end is always {"name":"Rex"}
and doesn’t include the animalType
fieldGilles Barbier
11/05/2020, 5:31 PMfun <T : Any> getSerializer(obj: T) : KSerializer<T>? {
val companionField = obj::class.java.declaredFields.find {
it.name == "Companion" && isStatic(it.modifiers)
} ?: return null
val companion = companionField.get(obj)
val serializerMethod = try {
companion::class.java.getMethod("serializer")
} catch (e: NoSuchMethodException) {
return null
}
if (serializerMethod.returnType.name != KSerializer::class.qualifiedName) {
return null
}
@Suppress("UNCHECKED_CAST")
return serializerMethod.invoke(companion) as KSerializer<T>
}
Is it the right way? It's seem a bit cumbersome to me. Why not to add an interface?Paul Woitaschek
11/06/2020, 6:20 AMtype
of the child classIvan Colovic
11/09/2020, 10:32 AMclass TreeNode(
val value: MyData
) {
val children = listOf<TreeNode>()
}
I’m trying to have the value
field named dynamically based on its type (many classes inherit from MyData
). Something like:
{
"data_one":{
...
},
"children":[
{
"data_two":{
...
},
"children":[
{
"data_three":{
...
},
"children":[
]
},
{
"data_one":{
...
},
"children":[
]
}
]
}
]
}
How do I define the SerialDescriptor
element that represents the collection of its own type? Right now, I have:
override val descriptor: SerialDescriptor = buildClassSerialDescriptor("TreeNode") {
element<DataOne>("data_one")
element<DataTwo>("data_two")
element<DataThree>("data_three")
element("children", listSerialDescriptor<TreeNode>()) // this crashes because I'm trying to use the descriptor I'm currently creating
}
When I change the listSerialDescriptor<TreeNode>()
to for example listSerialDescriptor<String>()
it encodes it the way I want it to, but I'm getting errors when decoding.
How do I approach this? Still new to the library I hope I was clear enough 🙇♂️ Thanks!Marc Plano-Lesay
11/12/2020, 2:37 AMJsonDecodingException
and MissingFieldException
being visible to slightly alter my error messages. They're now internal (defined here: https://github.com/Kotlin/kotlinx.serialization/blob/v1.0.1/core/commonMain/src/kotlinx/serialization/SerializationException.kt). Is there a way to get that distinction post 0.20?Nish Patel
11/12/2020, 5:15 PMpajatopmr
11/13/2020, 1:55 PMEmerson Farrugia
11/17/2020, 10:11 AMbram93
11/17/2020, 7:39 PMkottlinx.serialization
be utilized to parse a GraphQLType
(from graphql-java) and map it to a POJO without reflection costs? Using a custom format of some sort?bbaldino
11/17/2020, 10:22 PM@Serializable
types? I have a method that I want to be able to accept any type (Int, Boolean, some object, etc.) such that it can be serialized to Json via encodeToString
Shan
11/18/2020, 7:29 PMserializer()
function is not being recognized, nor the @Serializable
annotation, but the dependencies are being built correctly and everything works as intended. The @Serializable
annotation has a warning that the Kotlinx.Serialization compiler plugin is not applied to the module (which is not true), and the Foo.serializer()
function is showing up as not being found (I'm assuming as a result of Intellij thinking that the kotlinx.serialization compile plugin not being applied). Anyone know how to fix this? I've updated my Intellij to the latest version, as well as Kotlinx.Serialization library to no avail.Igor Brishkoski
11/20/2020, 9:23 PMList<Any>
and it works fine when I try to encode/decode the list on it’s own with Json
When I added it to my class, which is a member of a sealed class, 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
@Serializable
@SerialName("Sign")
data class Sign(
@Serializable(with = ListAnySerializer::class)
val payload: List<Any>
) : SealedClass()
jaguililla
11/21/2020, 4:35 PMkotlinx.serialization
provides the functionality to convert a Map
to a type as Jackson’s ObjectMapper.convertValue
do? Thanks!BollywoodVillain
11/23/2020, 5:46 PM@Serializable
data class while encoding?
e.g. Given a data class: data class MyClass(val accessible: Boolean)
and given the input JSON { "accessible": "yes" }
, can we convert the accessible
to Boolean
from String
while encoding?BollywoodVillain
11/24/2020, 7:00 AM{
"type": "node",
"id": 66917229,
"lat": 52.5167295,
"lon": 13.3797732,
"tags": {
"addr:city": "Berlin",
"addr:housenumber": "4a",
"addr:postcode": "10117",
"addr:street": "Pariser Platz",
"amenity": "cafe",
"brand": "Starbucks",
"name": "Starbucks",
"website": "<https://www.starbucks.de/store-locator/store/2099/pariser-platz-pariser-platz-4-a-berlin-be-10117-de>",
"wheelchair": "yes",
"wifi": "free"
}
}
I am using custom Serializer but I’m a bit lost on how to unwrap the nested values in the deserialize
function for the nested tags element. Any help is highly appreciated.Chris Ruddell
11/24/2020, 4:34 PM@Serializable
? I have a lot of classes marked with @Serializable
, but would like to have a single function to serialize them into JSON. For instance, something like
fun Any.toJson(): String = serializer.encodeToString(this)
Here’s what I’ve tried:
class JsonTest {
val serializer = Json {
serializersModule = SerializersModule {
contextual(MyModel.serializer())
}
}
// this works
fun MyModel.toModelJson(): String = serializer.encodeToString(this)
// this does not
fun Any.toJson(): String = serializer.encodeToString(this)
@Serializable
data class MyModel (val name: String)
@Test
fun testJson() {
val model = MyModel("test")
val modelJson = model.toModelJson()
assertTrue(modelJson.isNotEmpty())
val genericJson = model.toJson()
assertTrue(genericJson.isNotEmpty())
}
}
Exception thrown:
kotlinx.serialization.SerializationException: Serializer for class 'Any' is not found.
TwoClocks
11/24/2020, 7:48 PMrocketraman
12/01/2020, 2:52 PMCustomCoder
implementation that can handle any @Serializable
. Avro4k needs a KSerializer<T>
. How can I obtain the KSerializer
at runtime? Keep in mind that in Beam Coder
needs to be serializable itself, so KSerializer
or KType
cannot be a property of the coder i.e. this does not work, nor does passing in `KType`:
class Avro4kCoder<T: Any>(private val serializer: KSerializer<T>): CustomCoder<T>() {
override fun encode(value: T, outStream: OutputStream) {
Avro.default.openOutputStream(serializer) {
encodeFormat = AvroEncodeFormat.Binary
}.to(outStream).write(value).flush()
}
override fun decode(inStream: InputStream): T? {
return Avro.default.openInputStream(serializer) {
decodeFormat = AvroDecodeFormat.Binary(Avro.default.schema(serializer))
}.from(inStream).next()
}
}
rocketraman
12/01/2020, 6:47 PMval stringToColorMapSerializer: KSerializer<Map<String, Color>> = serializer()
However, is it possible to retrieve a serializer generically?
Since class
definitions can't have reified T
, the normal workaround is to pass in a Class<T>
. If I know that T
is an @Serializable
can I get the KSerializer<T>
from Class<T>
?Chris Fillmore
12/03/2020, 4:18 PMheaders
, which I can get from toMap()
Thomas
12/03/2020, 8:20 PMByron Katz
12/05/2020, 5:08 PMpajatopmr
12/06/2020, 3:29 PMsomeProvider?: boolean | string | SomeOptions;
My current solution is to create a sealed class SomeProvider
with subclasses: BooleanProvider
, StringProvider
, and OptionsProvider
so that I have the Kotlin snippet, someProvider: SomeProvider?
which works but feels sub-optimal. Alternative suggestions much appreciated.pajatopmr
12/06/2020, 3:29 PMsomeProvider?: boolean | string | SomeOptions;
My current solution is to create a sealed class SomeProvider
with subclasses: BooleanProvider
, StringProvider
, and OptionsProvider
so that I have the Kotlin snippet, someProvider: SomeProvider?
which works but feels sub-optimal. Alternative suggestions much appreciated.andylamax
12/06/2020, 9:03 PMpajatopmr
12/06/2020, 9:57 PM