kotlinx.serialization
kotlinx.serialization copied to clipboard
Computed property not serialize
A data class with computed property:
data class Bean(val name: String) {
val computed: String
get() = "--$name"
}
Use `kotlinx-serialization-runtime-0.20.0':
val result = Json(Stable).stringify(Bean.serializer(), Bean(name = "rj"))
the result is {"name":"rj"}
but I want it to be {"name":"rj","computed":"--rj"}
. How?
It is not supported yet because it is quite a rare use case
I need this feature also.
Example use case: my image urls are computed and not stored in the database.
Same for me.
The server adds computed properties to certain data classes to have their logic server-side instead of client-side.
Also #1578
This is still open?
Here is our use case. We have various projects written in multiple languages and legacy projects we cannot replace. Consider we have simple data classes like:
data class Person(val firstName: String, val lastName: String) {
val fullName get() = "$firstName $lastName"
}
And a legacy system expects a JSON payload with all 3 properties: firstName
, lastName
, and fullName
because it will persist in some DB as is.
There is no sense in deserializing the getter but, still useful to serialize its value for legacy systems.
In some other serialization libraries serializing getters and ignoring them on serialization is a normal practice.
Is there any workaround for kotlinx.serialization
?
I need this feature also.
Example use case: my image urls are computed and not stored in the database.
We have both! 😁 Both are computed and stored in the DB as well.
I solved it this way:
@Serializable
data class Person(
val firstName: String,
val lastName: String,
@SerialName("fullName ")
var _fullName = "") {
val fullName get() = _fullName
init {
_fullName get() = "$firstName $lastName"
}
}
Do you see any contraindications?
@felipeleon73 I would go with a serialization delegate (a private nested data class) that is used with a custom serializer to serialize instances (you can write the actual serialization code by hand, your choice).
@pdvrieze Use hand-written serializer is a huge work for the minor case.
@pdvrieze Use hand-written serializer is a huge work for the minor case.
That is why I would suggest a delegate
@pdvrieze Copy all fields also a huge work, when you have tens of fields. 😢