从redis中的字符串反序列化kotlin中的可选

时间:2018-12-17 21:59:08

标签: kotlin jackson jackson-databind

我正在尝试反序列化我在redis中另存为字符串的可选内容,但是我总是返回一个hashmap。 我正在实例化对象映射器

 private  var objectMapper: ObjectMapper= ObjectMapper().registerModule(KotlinModule())
        .registerModule( Jdk8Module())
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

序列化asi

  redisTemplate.opsForValue().set("key3", objectMapper.writeValueAsString(value))

我是deserializo asi:

var result1 = objectMapper.readValue<Optional<T>>(valueCache!!)

结果是

enter image description here

其中T是用户类

UserRole类:可序列化的{

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
var id: Long = 0

@Min(value = 1)
@JsonProperty("role_id")
@JoinColumn(name = "role_id", updatable = false, nullable = false)
var roleId: Long = 0

}

1 个答案:

答案 0 :(得分:0)

您报告的内容看起来不正确,我尝试了您的代码,它可以按预期工作。请检查以下代码段:

data class Role(val id: String, val name: String)
data class User(val id: String, val name: String, val email: String, val phone: String, val roles: List<Role>)


val objectMapper: ObjectMapper = ObjectMapper().registerModule(KotlinModule())
    .registerModule(Jdk8Module())
    .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

val json = """
    {
        "id": "1",
        "name": "John Smith",
        "email": "john@smith@mail.com",
        "phone": "+1-541-754-3010",
        "roles": [
            {"id": "1", "name": "User"},
            {"id": "1", "name": "Editor"},
            {"id": "1", "name": "Admin"}
        ]
    }
""".trimIndent()

val result = objectMapper.readValue<Optional<User>>(json)
println(result)

输出

  

可选[用户(id = 1,名称=约翰·史密斯,电子邮件= john @ smith @ mail.com,电话= + 1-541-754-3010,角色= [角色(id = 1,名称=用户) ,Role(id = 1,name = Editor),Role(id = 1,name = Admin)])]

调试检查确实报告了正确的类型

enter image description here