我在这里创建自定义序列化器:
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);
}
}
Your DataHolder
class :
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
format.
EDIT :
配置ObjectMapper
使用序列化器全局注册模块:
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。如果您不希望 getter 和 setter 配置 objectMapper 并设置字段可见性:
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);