Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
718 views
in Technique[技术] by (71.8m points)

dictionary - Jackson: Deserialize Map key which is another JSON entity

I have inherited a project. So far it uses something binary for serialization.
I would like to flip the serialization to JSON / Jackson.

The model has a "beautiful" construct stored into the database:
A Map whose key is another entity (ExternalId) with several properties.
ExternalId itself is also stored to a database.

To make it a bit funnier, ExternalId is a superclass with 4 subclasses, which I map using @JsonTypeInfo and @JsonTypeName. That works.

Now, there is that Map<ExternalId, BigDecimal> (sic). And Jackson tells me:

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
  },

In "...toString()" there is the result of ExternalId#toString().
So, I need to serialize and deserialize ExternalId.

Can I use Jackson and the same ObjectMapper for that?

Because, for that, it would get kind of recursively defined:

    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)
    }
}
question from:https://stackoverflow.com/questions/65930642/jackson-deserialize-map-key-which-is-another-json-entity

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...