Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin data class + Gson: optional field

Tags:

gson

kotlin

I have the following data class in Kotlin:

import com.google.gson.annotations.SerializedName

data class RouteGroup(
    @SerializedName("name") var name: String,
    @SerializedName("id") var id: Int
)

Sometimes I need to create an object with both fields, sometimes with only one of them.

How can I do this?

EDIT

This is not the duplicate of this question: Can Kotlin data class have more than one constructor? That question shows how to set a default value for a field. But in my case, I don't need to serialize the field with the default value. I want a field to be serialized only when I explicitly assign a value to it.

like image 581
Vitali Plagov Avatar asked May 20 '26 07:05

Vitali Plagov


2 Answers

it is easy you have to use the nullable operator

import com.google.gson.annotations.SerializedName

data class RouteGroup @JvmOverloads constructor(
    @SerializedName("name") var name: String? = null,
    @SerializedName("id") var id: Int? = null
)
like image 60
gmetax Avatar answered May 23 '26 09:05

gmetax


You may need something like this:

sealed class RouteGroup

data class RouteGroupWithName(
    @SerializedName("name") var name: String
) : RouteGroup()

data class RouteGroupWithId(
    @SerializedName("id") var id: Int
) : RouteGroup()

data class RouteGroupWithNameAndId(
    @SerializedName("name") var name: String,
    @SerializedName("id") var id: Int
) : RouteGroup()

EDIT 1:

Or you can use nullable fields and named parameters like this:

data class RouteGroup(
    @SerializedName("name") var name: String? = null,
    @SerializedName("id") var id: Int? = null
)

val routeGroupWithName = RouteGroup(name = "example")
val routeGroupWithId = RouteGroup(id = 2)
val routeGroupWithNameAndId = RouteGroup(id = 2, name = "example")
like image 44
TheKarlo95 Avatar answered May 23 '26 08:05

TheKarlo95