Json.encodeToString() does not include a property of enum type when it has a default value
See original GitHub issueDefault properties of an enum type are not included in JSON payloads when converted using Json.encodeToString()
The following snippet prints {}
instead of expected {"status":"OFFLINE"}
:
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
enum class Status { ONLINE, OFFLINE }
@Serializable
data class User(val status: Status = Status.OFFLINE)
fun main() {
println(Json.encodeToString(User()))
}
If I remove a default parameter from the User
class and create a user passing status, this would print the expected result of {"status":"OFFLINE"}
:
@Serializable
data class User(val status: Status)
fun main() {
println(Json.encodeToString(User(Status.OFFLINE)))
}
Environment
- Kotlin version:
1.5.31
- Library version:
1.3.0
- Kotlin platforms:
JVM
- Gradle version:
7.1
Issue Analytics
- State:
- Created 2 years ago
- Comments:5 (2 by maintainers)
Top Results From Across the Web
encodeToString not working when using a data class ... - GitHub
encodeToString doesn't work when a data class has a default value. Default values are not included in JSON strings. It works on 1.0.0-RC....
Read more >Excluding enum properties with default values in json response
This is resolved doing two things 1. Make the enum property as nullable and initialized it in the constructor to null. 2. Use...
Read more >EncodeDefault - Kotlin
EncodeDefault Controls whether the target property is serialized when its value is equal to a default value, regardless of the format settings. Does...
Read more >kotlinx.serialization: (de)serializing JSON's nullable, optional ...
If a property is given a default value, then kotlinx.serialization automatically considers it to be optional. Thus, if our optional property ...
Read more >Android Data Serialization Tutorial with the Kotlin Serialization ...
Then, the serializer() is used to encode the object into JSON. The transient property is not encoded or included in the JSON.
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
@pdvrieze I understand. I believe it shouldn’t be a default behavior.
This seems to work just like expected: https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/basic-serialization.md#defaults-are-not-encoded
You can enable serialization of defaults: https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/json.md#encoding-defaults