ankushg
08/31/2021, 11:36 PM{
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{
"value": "New",
"onclick": "CreateDoc()"
},
{
"value": "Open",
"onclick": "OpenDoc()"
},
{
"value": "Save",
"onclick": "SaveDoc()"
}
]
}
}
I'd like to represent it with a data class Menu(val id: String, val value: String, val popup: String)
where the popup
subtree is stored as a String of valid JSON, instead of having to deserialize the whole nested popup
structure.
Happy to write a custom serializer for this because it doesn't happen too frequently in our codebase.Pitel
09/01/2021, 11:42 AM{noQuote: "foobar"}
nilTheDev
09/03/2021, 7:56 AMEric Ampire [MOD]
09/03/2021, 2:17 PMUser
I can retrieved Users using two different end-points,
The first one return recent
users and the second one return popular
users, for both popular and recent end-points the data returning by the API has the same structure except one thing
The recent end-point return a json like this, that differ from the popular end-point at the recent field
{
"data": {
"recent": { ... } // Here the difference
}
}
And the popular end-point return a json like this, that differ from the recent end-point at the popular field
{
"data": {
"popular": { ... } // Here the different
}
}
Here the class hierarchy
@Serializable
data class ApiResponse(
@SerialName("data")
val apiData: Data
)
@Serializable
data class Data(
@SerialName("recent") // My problem is here
val page: Page
)
@Serializable
data class Page(
val currentPage: Int,
val from: Int,
val perPage: Int,
val results: List<User>,
)
For the Data
class, there is a way to customize the behavior of the SerialName
annotation to deal both with recent and popular name as the Page
class has the same structure for recent and popular end-point without having to duplicate stuff ??Eric Ampire [MOD]
09/04/2021, 3:23 AMCan't use arguments with defaults for serializable annotations yet
every time I use @JsonNames
annotation
Kotlin=1.5.21
Ktor=1.6.3
I'm not using the latest version of Kotlin because my project uses Jetpack Compose
The root cause java.lang.IllegalArgumentException was thrown at: org.jetbrains.kotlinx.serialization.compiler.backend.jvm.SerializerCodegenImpl.addSyntheticAnnotationsToDescriptor(SerializerCodegenImpl.kt:123)
sandwwraith
09/06/2021, 3:47 PM1.3.0-RC
has been released! It contains a lot of interesting features and improvements, such as:
• Integration with Java streams;
• Property-level control over defaults values encoding;
• Per-hierarchy polymorphic class discriminators;
• Excluding null values from JSON serialization.
You're welcome to evaluate it and share your feedback.
Full release notes here: https://github.com/Kotlin/kotlinx.serialization/releases/tag/v1.3.0-RCAyfri
09/06/2021, 8:14 PMException in thread "main" kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 0: Expected end of the object '}', but had '{' instead
JSON input: {"keywords":[],"softKeywords":[],"modifierKeywords":[],"specialIdentifiers":[],"operators":[]}
at kotlinx.serialization.json.internal.JsonExceptionsKt.JsonDecodingException(JsonExceptions.kt:24)
at kotlinx.serialization.json.internal.JsonExceptionsKt.JsonDecodingException(JsonExceptions.kt:32)
at kotlinx.serialization.json.internal.JsonLexer.fail(JsonLexer.kt:493)
at kotlinx.serialization.json.internal.JsonLexer.fail(JsonLexer.kt:215)
sushma nayak
09/08/2021, 12:32 PM"response":{
"value":5
}"
Value can be Int or string or a list of some other type.Justin Tullgren
09/09/2021, 5:31 PMserialVersionUID
completely unnecessary when saving to disk using serialization and then deserializing to a potentially modified class type later?Emil Kantis
09/09/2021, 7:34 PM@Serializable
and getting the following (in thread) exception from compiler when building.. Danish Ansari
09/12/2021, 9:43 AM{}
Easiest way to reproduce this issue is to try official generic classes example, add data
modifier to the class and have default value (eg. in thread)
https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/basic-serialization.md#generic-classes
I'm using kotlinx.serialization v1.2.2 and Kotlin v1.5.21
Update: All I had to do was read this section of doc 😅https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/json.md#encoding-defaultsEmil Kantis
09/13/2021, 2:55 PMorg.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: Couldn't transform method node:
write$Self (Ldev/kantis/Square;Lkotlinx/serialization/encoding/CompositeEncoder;Lkotlinx/serialization/descriptors/SerialDescriptor;Lkotlinx/serialization/KSerializer;Lkotlinx/serialization/KSerializer;)V:
@Lkotlin/jvm/JvmStatic;()
// annotable parameter count: 5 (visible)
// annotable parameter count: 5 (invisible)
@Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 0
@Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 1
@Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 2
@Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 3
@Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 4
[Full error in thread]
Chachako
09/14/2021, 3:57 PMstars
is not encoded to json❓Chachako
09/16/2021, 4:09 AMSergey Akhapkin
09/17/2021, 1:33 PM@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
sealed class A {
@JsonTypeName("B")
object B: A()
@JsonTypeName("C")
object C: A()
@JsonTypeName("D")
data class D(val i: Int): A()
}
class JsonTest {
private val objectMapper = jacksonObjectMapper().apply(configureObjectMapper)
private fun <T> parse(str: String, clazz: Class<T>): T = objectMapper.readValue(str, clazz)
private fun <T> stringify(value: T): String = objectMapper.writeValueAsString(value)
@Test
fun testPatternMatching() {
val x1 = A.B
val x2 = parse(stringify(x1), A::class.java)
val x3 = A.C
listOf(x1,x2,x3).forEach {
when(it) {
A.B -> println("b ${it as Any}")
A.C -> println("c ${it as Any}")
is A.D -> println("d ${it as Any}")
else -> println("? ${it as Any}")
}
}
assertEquals(A.B, x1)
assertEquals(A.B, x2) // <--- failed assertion in 1.4.30
assertEquals(x1, x2)
}
}
In 1.3.50 projects, it prints:
b com.example.A$B@184a254d
b com.example.A$B@184a254d
c com.example.A$C@41443428
In 1.4.30 (and 1.5.x) projects, it prints:
b com.example.A$B@12a1cc8d
? com.example.A$B@7b2edf94
c com.example.A$C@73baae4e
and test fails with
expected:<com.example.A$B@12a1cc8d> but was:<com.example.A$B@7b2edf94>
As I can see - after serialization/deserialation I got 2nd A.B object (nonsense for a singleton). This code can be fixed by writting 'is A.B', in that case both instances (x1 and x2) will be matched.
But who knows what is going on here and why it changed since 1.4.x ?Narek Mailian
09/21/2021, 4:58 PM@Serializable
data class ProjectIdWrapper(
val id: ProjectId,
val item: Project)
@Serializable
data class Project(
val projectProperty1: String,
val projectProperty2: String
)
but I want to have ProjectIdWrapper serialized/deserialized as
{
"id": 12121,
"projectProperty1": "AAA",
"projectProperty2": "BBB"
}
Is this possible? Or even better, can the IdWrapper be made generic? 😊Moritz Post
09/22/2021, 2:30 PM["create", true, {more: "properties"]
. There are more types than just the "create"
shown here. I have attempted many different approaches but none were successful so far. What would be the best approach for such an input?Jan
09/22/2021, 2:31 PMException in thread "DefaultDispatcher-worker-10" kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 14: Expected beginning of the string, but got ,
JSON input: {"type":"rich","author":{"name":"author"}}
Moritz Post
09/23/2021, 10:24 AMoverride val descriptor: SerialDescriptor = buildSerialDescriptor("Create", StructureKind.LIST) {
element("target", serialDescriptor<String>())
element("method", serialDescriptor<String>())
element("properties", serialDescriptor<Map<String, Any>>())
}
The remaining problem now is the Map<String, Any> part where i want to resolve the properties into a Map with properties and possible sublists. However there is not serializer for Any
. Any advice on how to serialize the Any correctly within the properties map?Евгений Попович
09/23/2021, 12:36 PM@Serializable
data class ReportUserResponse(
val message: String,
val code: Int,
)
without having to create another class with a 'response' field
?Daniele B
09/24/2021, 1:24 AM@Serializable
data class RpcRequest(
@SerialName("jsonrpc") val jsonrpc : String,
@SerialName("id") val id : Int,
@SerialName("method") val method : String,
@SerialName("params") val params : List<@Contextual Any>?,
)
where params
could be a list of any kind of object
I currently get this error:
Serializer for class 'Any' is not found.
Mark the class as @Serializable or provide the serializer explicitly.
An example of RpcRequest object:
val req = RpcRequest("2.0",2342,"getData",listOf("erwrwee",{"encoding":"base64"}))
How can it be properly serialized?Moritz Post
09/24/2021, 3:19 PMnordiauwu
09/25/2021, 2:18 PMaltavir
09/27/2021, 9:37 AMsandwwraith
09/27/2021, 10:43 AM1.3.0
has been released! This release brings a lot of new features, such as preview of <http://java.io|java.io>.*Stream
-based serialization, additional control over default and nullable properties, and more. Check out the blogpost and the changelog:
https://blog.jetbrains.com/kotlin/2021/09/kotlinx-serialization-1-3-released/
https://github.com/Kotlin/kotlinx.serialization/blob/v1.3.0/CHANGELOG.mdDidier Villevalois
09/27/2021, 3:41 PMJsonContentPolymorphicSerializer
to manually select what de-serializer to use for my polymorphic class hierarchies, while using JsonTransformingSerializer
to remove the type
fields at serialization.
I am doing this:
inline fun <reified T : Any> noDiscriminatorPolymorphic(crossinline serializerSelector: (element: JsonElement) -> DeserializationStrategy<out T>): KSerializer<T> {
val serializer = object : JsonContentPolymorphicSerializer<T>(T::class) {
override fun selectDeserializer(element: JsonElement): DeserializationStrategy<out T> {
return serializerSelector(element)
}
}
return NoDiscriminantSerializer(serializer)
}
class NoDiscriminantSerializer<T : Any>(serializer: KSerializer<T>) :
JsonTransformingSerializer<T>(serializer) {
override fun transformSerialize(element: JsonElement): JsonElement {
val content =
element.jsonObject.mapValues { (_, v) -> if (v is JsonObject) JsonObject(v.jsonObject - "type") else v } - "type"
return super.transformSerialize(JsonObject(content))
}
}
and then this:
val myFormat = Json {
serializersModule = SerializersModule {
contextual(noDiscriminatorPolymorphic { element ->
when {
"thisField" in element.jsonObject -> ThisClass.serializer()
"thatField" in element.jsonObject -> ThatClass.serializer()
else -> error("Unknown subclass")
}
})
}
}
But the type
fields are always serialized. Does anyone know what I am missing?rnentjes
09/28/2021, 8:33 AMException in thread "main" java.lang.NoSuchMethodError: 'void kotlinx.serialization.json.JsonBuilder.setExplicitNulls(boolean)'
at com.banktrade.sequoia.serialization.SerializationConfig$updateSerialFormat$1.invoke(SerializationConfig.kt:55)
at com.banktrade.sequoia.serialization.SerializationConfig$updateSerialFormat$1.invoke(SerializationConfig.kt:47)
at kotlinx.serialization.json.JsonKt.Json(Json.kt:137)
at kotlinx.serialization.json.JsonKt.Json$default(Json.kt:135)
Anyone else tried this one out already?kevin.cianfarini
09/28/2021, 12:44 PM@Serializable(with = RepresentedAreaSerializer::class)
enum class RepresentedArea(override val value: String) : StringEnum {
Alaska("AK"),
Alabama("AL"),
AmericanSamoa("AS")
...
}
object RepresentedAreaSerializer : StringEnumSerializer(RepresentedArea.values())
abstract class StringEnumSerializer<T>(
enumValues: Array<out T>,
) : KSerializer<T> where T : StringEnum, T : Enum<T> {
private val enumMap = enumValues.associateBy { it.value }
override val descriptor get() = PrimitiveSerialDescriptor("StringEnumSerializer", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: T) = encoder.encodeString(value.value)
override fun deserialize(decoder: Decoder): T = checkNotNull(enumMap[decoder.decodeString()])
}
When I try to serialize this value with the following method, I get an error that Serializer for class 'RepresentedArea' is not found.
@Test fun foo() {
val json = Json { prettyPrint = true}
assertEquals("VA", json.encodeToString(RepresentedArea.Virginia)) // runtime error
}
The strange bit is that I can serialize it as a part of other object structures. For example, the following works for both serializing and deserializing.
@Serializable class GetLegislatorsByAddressRequest(
val streetAddress: String,
val city: String,
val state: RepresentedArea,
val postalCode: String,
)
I'm a bit stuck on this error. Does anyone have any ideas what I'm doing wrong?Richard Gomez
10/02/2021, 12:20 AMJsonObject
to Map<String, Any>
, but am stumped on JsonPrimitive
.
It stores all values as String
, so it doesn't seem possible to get a float/boolean/etc. unless you know its type ahead of time.
Is there a (simpler) way to accomplish this?Matthew Cachia
10/06/2021, 4:35 PMMatthew Cachia
10/06/2021, 4:35 PMsandwwraith
10/07/2021, 10:37 AMMatthew Cachia
10/07/2021, 10:41 AMobject JsonEleTransformer = ...
val jsonEle = json.parseToJsonElement("{...}")
val transformedJsonEle = json.decodeFromJsonElement(JsonEleTransformer, jsonEle)
val t:T = json.decodeFromJsonElement(transformedJsonEle)
It works. Thank you just the same.sandwwraith
10/07/2021, 10:41 AM