Here I am creating custom Serializer :
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;
}
}
And Main class for testing :
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);
}
}
The output is :
{"expectedData":"Hello world"}
Please keep in mind that you should use encoding thats is suitable for you. If your byte[]
array does not represent anything readable you should keep it in base64
format.
EDIT :
To configure ObjectMapper
globally register module with Serializer for it :
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);
}
}
Remember to provide getters and setters for your data. If you dont want getters and setters configure objectMapper and set field visibility :
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);