gson 使用Kotlin限制序列化类属性允许的整数值

bfnvny8b  于 6个月前  发布在  Kotlin
关注(0)|答案(1)|浏览(94)

我想限制类属性允许的整数值,在序列化为Json(使用gson)后,值将表示为数字而不是字符串。

class Car(
@Expose val color: Color = Color.RED,
@Expose val seats: Seats = Seats.FIVE   // Using an enum class so only predefined values are accepted.
)

enum class Color{
     @SerializedName("red") RED,
     @SerializedName("blue") BLUE,
}

enum class Seats{
     @SerializedName("4") FOUR,
     @SerializedName("5") FIVE,
}

字符串
实际json输出:

{
   "color": "red",
   "seats": "5"   // This is a string. It's not what I want.
}


我需要的json输出:

{
   "color": "red",
   "seats": 5   // This is a number ✓
}

wi3ka0sx

wi3ka0sx1#

如果你真的想坚持使用Gson,一种方法是将整数指定为枚举的属性:

enum class Seats(val value: Int) {
    FOUR(4),
    FIVE(5);

    companion object {
        fun of(value: Int) = entries.firstOrNull { it.value == value }
    }
}

字符串
然后使用类型适配器或自定义序列化程序,使用此属性进行序列化,并使用Seat.of(...)函数进行序列化:

class SeatSerializer : JsonSerializer<Seats> {
    override fun serialize(src: Seats, typeOfSrc: Type, context: JsonSerializationContext): JsonElement =
        JsonPrimitive(src.value)
}

class SeatDeserializer : JsonDeserializer<Seats> {
    override fun deserialize(element: JsonElement, type: Type, context: JsonDeserializationContext): Seats =
        Seats.of(element.asInt) ?: error("Cannot deserialize ${element.asInt} as Seats")
}

相关问题