user405398
user405398

Reputation:

How to configure jackson to not to serialize byte array?

I have an JSON like object, which also has some binary values. I do not want the binary(byte[]) data to be serialized.

I have tried to add custom serializer for byte[]. But it didn't worked out.

Try 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("");
    }

}

Try 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("");
    }

}

But, both are failing to override the default serializer.

I could not use annotation because, its a Map<Object, Object>.

Thanks.

Upvotes: 1

Views: 2954

Answers (1)

Yair Zaslavsky
Yair Zaslavsky

Reputation: 4137

Have you tried using the JsonIgnore annotation on the getter or the field itself? You can also use MixIn in order to do that. Example (taken from oVirt open source):

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();
}

And the usage is at JSonObjectSerializer (copying paste a part of it here)

@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);
    }

Upvotes: 1

Related Questions