kotlin使用jackson序列化enum

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

默认情况下,我们序列化与反序列化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())

输出

{"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)

转载于:https://my.oschina.net/weidedong/blog/3002932

你可能感兴趣的:(移动开发,json,python)