Let's say I want to serialize Boolean
into Number
by default.
I know I can do it field-by-field
@JsonFormat(shape = Shape.NUMBER)
private Boolean success;
But can I "register" my custom Serializer so that when I return an Object from my API, the Boolean
s in the class will be serialized into Number
in the json response.
I have the following Serializer
public class MyBooleanSerializer extends JsonSerializer<Boolean> {
@Override
public void serialize(
Boolean value,
JsonGenerator gen,
SerializerProvider serializers) throws IOException {
gen.writeString(value ? "1" : "0");
}
}
And I have the following class
@Data
public class MyResponse {
private Boolean success;
private String message;
}
It will be used like this
@GetMapping("/hello")
public MyResponse hello() {
Boolean success = true;
String message = "Hi there";
return new MyResponse(success, message);
}
And when I GET
this API, I am expecting this response
{
success: 1,
message: "Hi there"
}
I am expecting some Beans to be injected. I have tried
@Bean
@Primary
ObjectMapper objectMapper() {
SimpleModule module = new SimpleModule();
module.addSerializer(new MyBooleanSerializer());
return new ObjectMapper()
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
.registerModule(module);
}
but it does not work.
I have read this tutorial and seems like it needs to create the jsonMapper
every time I want to serialize an object. All I want is whenever I return MyResponse
from an API, the Boolean
s are serialized into Number
s.
Thanks.
CodePudding user response:
Because of the serializer, the boolean value is converted into the form of true or false public class NumericBooleanSerializer extends JsonSerializer {
public void serialize(Boolean b, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeNumber(b ? 1 : 0);
}
} hat will serialize booleans as 1 or 0.
CodePudding user response:
Can be done with a custom StdSerializer
like
class CustomBooleanSerializer extends StdSerializer<Boolean> {
public CustomBooleanSerializer(){
super(Boolean.class);
}
@Override
public void serialize(Boolean value, JsonGenerator generator, SerializerProvider provider) throws IOException {
generator.writeNumber(value ? 1 : 0);
}
}
And configure this via a Jackson2ObjectMapperBuilderCustomizer
@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return builder ->
builder.serializationInclusion(JsonInclude.Include.USE_DEFAULTS) // <-- optional
.serializers(new CustomBooleanSerializer());
}