java - 如何配置 Jackson 不序列化字节数组?

标签 java serialization arrays 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> .

谢谢。

最佳答案

您是否尝试过在 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/

相关文章:

java - 墙壁上的 Pong 反射

php - 如何在数组中查找并计算相同的值,然后插入包含 : ‘count: (int)’ via PHP? 的节点

javascript - 尝试在表格中显示数组(Javascript + html)

arrays - 为什么我的数组打印的是对象位置而不是值?

java - 赋值的左侧必须是变量错误

java - Tomcat 7 部署阻止我进行细微更改

java - Google Cloud Dataflow 用户定义的 MySQL 源

c# - MongoDb 自定义集合序列化器

java - 将 ArrayList 保存到文本文件时出现 NotSerializedException

java - 安卓 : Why occur "NotSerializableException" even if implements "Serialization"?