如何配置jackson不要序列化字节数组?

时间:2012-06-22 06:22:39

标签: java serialization bytearray jackson binary-data

我有一个类似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>

感谢。

1 个答案:

答案 0 :(得分:1)

您是否尝试在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);
    }