无法添加自定义杰克逊解串器?

时间:2017-10-17 13:27:00

标签: java json serialization jackson

我为Jackson构建了自定义java.security.Key序列化程序和反序列化程序。它们被声明为

public class KeySerializer extends JsonSerializer<Key>

public class KeyDeserializer extends JsonDeserializer<Key>

当我使用装饰器时:

@JsonSerialize(using = KeySerializer.class)
@JsonDeserialize(using = KeyDeserializer.class)
private PublicKey publicKey;

它工作得很好,但我试图在装饰器(据我所知)未应用(Hibernate JSON)的情况下使用它们。在这种情况下,我实际上有一个创建Object映射器的类:

public class JacksonUtil {
    public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
}

当我使用该对象映射器时,我收到错误:

为了使其工作,我注册了(de)序列化器,如下所示:

No serializer found for class org.bouncycastle.math.ec.WNafL2RMultiplier and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey["parameters"]->org.bouncycastle.jce.spec.ECParameterSpec["curve"]->org.bouncycastle.math.ec.custom.sec.SecP521R1Curve["multiplier"])

我认为它实质上是说BCECPublicKey没有序列化器。所以,我添加这样的(de)序列化器:

static {
    SimpleModule module = new SimpleModule();
    module.addSerializer(Key.class, new KeySerializer());
    OBJECT_MAPPER.registerModule(module);
    module = new SimpleModule();
    module.addDeserializer(Key.class, new KeyDeserializer());
    OBJECT_MAPPER.registerModule(module);
}

序列化似乎有效,但反序列化不起作用:

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)

该错误是正确的,但这就是为什么我创建了自己的反序列化器,它知道如何创建BCECPublicKey,但它没有被调用。

为什么我的自定义反序列化器没有被调用?

我也试着像这样添加它:

module = new SimpleModule();
module.addDeserializer(BCECPublicKey.class, new KeyDeserializer());
OBJECT_MAPPER.registerModule(module);

但是我收到了错误:

Error:(34, 15) java: method addDeserializer in class com.fasterxml.jackson.databind.module.SimpleModule cannot be applied to given types;
  required: java.lang.Class<T>,com.fasterxml.jackson.databind.JsonDeserializer<? extends T>
  found: java.lang.Class<org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey>,tech.dashman.common.crypto.KeyDeserializer
  reason: inference variable T has incompatible bounds
    equality constraints: org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey
    lower bounds: java.security.Key

BCECPublicKey实现了Key,实际上在我的测试中,这个解串器工作正常。这是怎么回事?

0 个答案:

没有答案