在Jackson ObjectMapper上序列化时禁用Base64编码

时间:2019-05-08 15:39:13

标签: java jackson objectmapper

我正在使用Jackson 2.2.3。当我将对象序列化为JSON时,所有byte[]属性都在生成的json中被编码为base64

如何禁用它?

这是我的代码。

DataHolder.java

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "expectedData"
})
@XmlRootElement(name = "dataHolder")
public class DataHolder {

    private final static long serialVersionUID = 1L;
    @XmlElement(required = true, type = String.class)
    @XmlJavaTypeAdapter(HexBinaryAdapter.class)
    @XmlSchemaType(name = "hexBinary")
    protected byte[] expectedData;

    ...

}

JSON输出:

{
...
"dataHolder": {
    "expectedData": "c29tZXRleHQ=",
}
...
}

1 个答案:

答案 0 :(得分:1)

在这里,我正在创建自定义序列化程序:

public class BytesToStringSerializer extends StdSerializer<byte[]> {

    public BytesToStringSerializer() {
        super(byte[].class);
    }

    protected BytesToStringSerializer(Class<byte[]> t) {
        super(t);
    }

    @Override
    public void serialize(byte[] value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        String yourReadableString = new String(value, StandardCharsets.UTF_8);
        gen.writeString(yourReadableString);
    }
}

您的DataHolder类:

public class DataHolder {
    @JsonSerialize(using = BytesToStringSerializer.class)
    byte[] expectedData;

    public DataHolder(byte[] expectedData) {
        this.expectedData = expectedData;
    }
}

用于测试的主类:

public class Main {
    public static void main(String[] args) throws JsonProcessingException {

        byte[] someBytes = "Hello world".getBytes(StandardCharsets.UTF_8);
        DataHolder dataHolder = new DataHolder(someBytes);
        ObjectMapper objectMapper = new ObjectMapper();
        String output = objectMapper.writeValueAsString(dataHolder);
        System.out.println(output);
    }
}

输出为:

{"expectedData":"Hello world"}

请记住,您应该使用适合自己的编码。如果您的byte[]数组不代表任何可读性,则应将其保留为base64格式。

编辑:

要为ObjectMapper的全局注册模块配置Serializer:

public class Main {
    public static void main(String[] args) throws JsonProcessingException {
        byte[] someBytes = "Hello world".getBytes(StandardCharsets.UTF_8);
        DataHolder dataHolder = new DataHolder(someBytes);

        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        module.addSerializer(byte[].class, new BytesToStringSerializer());
        objectMapper.registerModule(module);

        String output = objectMapper.writeValueAsString(dataHolder);
        System.out.println(output);
    }
}

请记住要为您的数据提供获取器和设置器。如果您不希望使用getter和setter来配置objectMapper并设置字段可见性:

objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);