针对特定类别中的特定类型的自定义Jackson Serializer [英] Custom Jackson Serializer for a specific type in a particular class
问题描述
杰克逊是否允许仅针对特定类别的特定类型进行自定义序列化?
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;
}
}
我无法访问此类,因为它是在一个外部罐子里。但是,我想以特定方式在此处序列化令牌字节数组。我已经创建了一个自定义序列化程序来执行该操作,并尝试以杰克逊文档中提到的所有方式将其添加到映射器。
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);
}
}
在mapper中,类似这样:
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中的ONLY 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中的字节数组属性/ code>。
Your custom serializer will be used only for serializing byte array property in ClassA
.
这篇关于针对特定类别中的特定类型的自定义Jackson Serializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!