问题描述
我继承了一个项目。到目前为止,它使用二进制进行序列化。
我想将序列化转换为 JSON/Jackson。
该模型有一个存储在数据库中的“漂亮”构造:
一个 Map
,其键是具有多个属性的另一个实体 (ExternalId
)。ExternalId
本身也存储到数据库中。
为了让它更有趣,ExternalId
是一个具有 4 个子类的超类,我使用 @JsonTypeInfo
和 @JsonTypeName
映射它们。那行得通。
现在是 Map<ExternalId,BigDecimal>
(原文如此)。杰克逊告诉我:
com.fasterxml.jackson.databind.exc.InvalidDeFinitionException:
Cannot find a (Map) Key deserializer for type [simple type,class com.iptiq.payment.id.ExternalId]
at [Source: (byte[])"{
"externalIdsWithAmount" : {
"...toString() of ExternalId..." : 20.00000000
},
在"...toString()"
中有ExternalId#toString()
的结果。
所以,我需要序列化和反序列化 ExternalId
。
我可以使用 Jackson 和相同的 ObjectMapper
吗?
因为,为此,它会得到某种递归定义:
val module = SimpleModule()
module.addKeySerializer(ExternalId::class.java,JacksonKeyDeserializers.Ser(mapper))
module.addKeyDeserializer(ExternalId::class.java,JacksonKeyDeserializers.Deser(mapper))
mapper.registerModule(module)
/**
* Serializes the key in Map<ExternalId,...> into a JSON string.
* The model is not too cLever,but that's what we have.
*/
class Ser(val mapper: ObjectMapper) : StdSerializer<ExternalId>(ExternalId::class.java) {
override fun serialize(value: ExternalId,gen: JsonGenerator,provider: SerializerProvider) {
gen.writeFieldName(mapper.writeValueAsstring(value))
}
}
class Deser(val mapper: ObjectMapper) : KeyDeserializer() {
@Throws(IOException::class,JsonProcessingException::class)
override fun deserializeKey(key: String,ctxt: DeserializationContext): ExternalId {
return mapper.readValue(key.toByteArray(),ExternalId::class.java)
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)