我想限制类属性允许的整数值,在序列化为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 ✓
}

推荐答案

如果您真的想坚持使用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")
}

Json相关问答推荐

服务器不返回JSON

组合不同属性的Jolt Spec

来自json的可分析的构建报告

如何在Android中解析带有动态键和可变对象名称的改装JSON响应?

Moshi:序列化 List 时出现问题

Jolt 不打印任何东西

使用 map_values Select 包含空格的字符串未按预期工作

jq - 将父键值提取为子元素旁边的逗号分隔值

每次在 SoapUI 中发送请求时,将 JSON 响应的子 node 分配给项目变量

将 JSON 字符串解析为 Kotlin Android 中的对象列表(MOSHI?)

修改 boost::json::object 中的值

使用杰克逊解析Kotlin 中的通用密封类

Json.NET SerializeObject 转义值以防止 XSS

如何一次加载无限滚动中的所有条目以解析python中的HTML

使用 JSON 的 javascript 深拷贝

Spring Security 和 JSON 身份验证

将序列化表单的数据转换为 json 对象

如何使用 Serde 反序列化带有自定义函数的可选字段?

IE10/11 Ajax XHR 错误 - SCRIPT7002:XMLHttpRequest:网络错误 0x2ef3

将对象序列化为 JSON 时循环引用检测到异常