默认情况下,我们序列化与反序列化enum是它的name,事实上大部分情况下我们需要序列化的是我们自定义的value,那应该怎么做呢?
这种情况下我们就需要@JsonValue与@JsonCreator
data class User(var id:Int = 0,
var name:String="",
var birthday:LocalDateTime? = null,
//@get:JsonProperty("orderID")
var orderId:String? = null,
var userType:UserType = UserType.ADMIN
)
enum class UserType(
//指定typeValue序列化
@get:JsonValue
val typeValue: Int
) {
ADMIN(2),
USER(4);
companion object {
//指定creator反序列化
@JsonCreator
@JvmStatic
fun creator(typeValue: Int):UserType{
val found = UserType.values().find { it.typeValue == typeValue }
return found ?: throw IllegalArgumentException("not found IconEnum with $typeValue")
}
}
}
那我们用jackson进行序列化及序列化操作,试一下
val u = User(1, "st", birthday = LocalDateTime.now(),orderId = "123",userType = UserType.ADMIN)
val json = u.toJson()
println(json)
println(json.fromJson<User>())
输出
{"id":1,"name":"st","birthday":"2019-01-17T20:08:58.515","orderId":"123","userType":2}
User(id=1, name=st, birthday=2019-01-17T20:08:58.515, orderId=123, userType=ADMIN)