Serialize enum to integer values

Viewed 718

I have the following enum:

enum class Scopes(val value: Int) {
    NODE(0),
    API(1),
    PROJECT(2),
    GLOBAL_TO_OWNER(3),
    PUBLIC_TO_ANYONE(4)
}

I would like to serialize this so that the enum value (its ordinal) is exported as an integer and not as a string. Example:

{"scope": 1}

What I don't want is:

{"scope": "1"}

If this can be done using Gson, that is preferred. If not, perhaps a native Kotlin approach might do.

1 Answers

simple override of serialize should do it

import com.google.gson.GsonBuilder
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.JsonSerializationContext
import com.google.gson.JsonSerializer
import java.lang.reflect.Type

enum class Scopes(val value: Int) : JsonSerializer<Scopes> {
    NODE(0), API(1), PROJECT(2), GLOBAL_TO_OWNER(3), PUBLIC_TO_ANYONE(4);

    override fun serialize(p0: Scopes?, p1: Type?, p2: JsonSerializationContext?): JsonElement =
        JsonObject().apply { addProperty(p0?.name, p0?.value) }
}

fun main(args: Array<String>) {
    val s = Scopes.NODE
    val gson = GsonBuilder().registerTypeAdapter(Scopes::class.java, Scopes.API).create()
    val jsonString = gson.toJson(s)
    println(jsonString)
}
Related