I have a data class that can be serialized into a json. Is it possible to also Serialize the class name by using something like the @SerialName? I know that I could achieve that by using another class that holds "File" as a property but I would like to avoid this as it would lead to a lot of wrapper classes in my project that feel unnecessary.
@Serializable
@SerialName("file")
data class File(
val name: String,
val version: Int,
val type: String
)
What I want the JSON to look like.
{ "file": { "name": "cv", "version": "1", "type": "pdf" }}
2
Answers
That’s not going to come about by changing
@SerialName
or another similar annotation. You need to write an alternativeKSerializer
(another class!), either by hand, or using a surrogate (a further new class). The surrogate approach doesn’t take long though and gets the job done without too much effort, albeit at the expense of the boilerplate code.If you are keen to have an elegant approach then I’d suggest writing a KSP plugin to process your own annotation. Of course, that’s only worthwhile if you’re going to be facing this issue often.
You need to create a custom serializer or compiler plugin as @simon-jacobs said but again you’ll end up having one more class.
If you don’t want to create another class, you can an existing one like a Map:
Output:
{ "file": { "name": "cv", "version": "1", "type": "pdf" }}