特定类中特定类型的自定义 Jackson Serializer [英] Custom Jackson Serializer for a specific type in a particular class
问题描述
Jackson 是否有一种方法允许仅在特定类中对特定类型进行自定义序列化?
Is there a way by which Jackson allows custom serialization for a specific type only in a particular class?
这是我的场景:我有 ClassA.java 类似于:
Here is my scenario: I have ClassA.java which is something like:
public Class ClassA {
byte[] token;
String name;
public getToken() {
return token;
}
public setToken(byte[] newToken) {
token = newToken;
}
public getName() {
return name;
}
public setName(String newName) {
name = newName;
}
}
我无权访问此类,因为它位于外部 jar 中.但是,我想以特定方式在此处序列化 token 字节数组.我创建了一个自定义序列化程序来执行此操作,并尝试以 Jackson 文档中提到的所有方式将其添加到映射器中.
I do not have access to this class as it is in an external jar. However, I want to serialize the token byte array here in a particular manner. I have created a Custom serializer that does that and tries adding it to the mapper in all the ways mentioned in Jackson docs.
public class ByteArrayJacksonSerializer extends JsonSerializer<byte[]> {
public void serialize(byte[] value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
String token = doMyThing(value);
jgen.writeString(token);
}
}
在映射器中,是这样的:
And in mapper, something like this:
public class MyObjectMapper extends ObjectMapper {
CustomSerializerFactory sf = new CustomSerializerFactory();
sf.addGenericMapping(byte[].class, new ByteArrayJacksonSerializer());
this.setSerializerFactory(sf);
and some more code here...
}
但是,我通常只能对 byte[] 执行此操作,而不能仅对 ClassA 中的 byte[] 执行此操作.有没有办法让杰克逊知道这个自定义序列化器必须仅用于 ClassA 中的 byte[] 类型的字段,并且要以自己的方式对所有其他类进行序列化?
However I can do it only for byte[] in general, and not for ONLY byte[] in ClassA. Is there a way to let Jackson know that this custom serializer must be used ONLY for fields of byte[] type in ClassA, and to do serialization it's own way for all other classes?
推荐答案
您应该使用 MixIn 功能.在您的示例中,您必须创建新界面:
You should use MixIn feature. In your example you have to create new interface:
interface ClassAMixIn {
@JsonSerialize(using = ByteArrayJacksonSerializer.class)
byte[] getToken();
}
为给定属性指定自定义序列化程序.现在我们必须配置ObjectMapper
which specifies custom serializer for given property. Now we have to configure ObjectMapper
ObjectMapper mapper = new ObjectMapper();
mapper.addMixInAnnotations(ClassA.class, ClassAMixIn.class);
您的自定义序列化程序将仅用于序列化 ClassA
中的字节数组属性.
Your custom serializer will be used only for serializing byte array property in ClassA
.
这篇关于特定类中特定类型的自定义 Jackson Serializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!