我有一个类似 JSON 的对象,它也有一些二进制值。
我不想序列化二进制( byte[]
)数据。
我尝试为byte[]
添加自定义序列化器。但没有成功。
尝试1:
public class ByteArraySerialiser extends SerializerBase<Byte[]> {
protected ByteArraySerialiser() {
super(Byte[].class, false);
}
@Override
public void serialize(Byte[] arg0, JsonGenerator arg1,
SerializerProvider arg2) throws IOException,
JsonGenerationException {
arg1.writeString("");
}
}
尝试 2:
public class ByteArraySerialiser extends SerializerBase<Byte> {
protected ByteArraySerialiser() {
super(Byte.class, false);
}
@Override
public void serialize(Byte arg0, JsonGenerator arg1,
SerializerProvider arg2) throws IOException,
JsonGenerationException {
arg1.writeString("");
}
}
但是,两者都无法覆盖默认序列化程序。
我无法使用注释,因为它是 Map<Object, Object>
.
谢谢。
最佳答案
您是否尝试过在 getter 或字段本身上使用 JsonIgnore 注释?
您还可以使用 MixIn 来做到这一点。示例(取自 oVirt 开源):
public abstract class JsonNGuidMixIn extends NGuid {
/**
* Tells Jackson that the constructor with the {@link String} argument is to be used to deserialize the entity,
* using the "uuid" property as the argument.
*
* @param candidate
*/
@JsonCreator
public JsonNGuidMixIn(@JsonProperty("uuid") String candidate) {
super(candidate);
}
/**
* Ignore this method since Jackson will try to recursively dereference it and fail to serialize.
*/
@JsonIgnore
@Override
public abstract Guid getValue();
}
用法在JSonObjectSerializer(复制粘贴其中的一部分)
@Override
public String serialize(Serializable payload) throws SerializationExeption {
ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().addMixInAnnotations(NGuid.class, JsonNGuidMixIn.class);
mapper.getSerializationConfig().addMixInAnnotations(Guid.class, JsonNGuidMixIn.class);
mapper.configure(Feature.INDENT_OUTPUT, true);
mapper.enableDefaultTyping();
return writeJsonAsString(payload, mapper);
}
关于java - 如何配置 Jackson 不序列化字节数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11151072/