【问题标题】:How to configure jackson to not to serialize byte array?如何配置杰克逊不序列化字节数组?
【发布时间】:2012-06-22 06:22:39
【问题描述】:

我有一个类似 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&lt;Object, Object&gt;

谢谢。

【问题讨论】:

    标签: java serialization bytearray jackson binary-data


    【解决方案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);
        }
    

    【讨论】:

      猜你喜欢
      • 2011-07-03
      • 2014-09-29
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-04
      相关资源
      最近更新 更多