I have a user dto class and i need to convert some of its properties before send it to frontend.
UsedDto class
JavaScript
x
public class UserDto {
protected Integer userId;
protected String userName;
protected String password;
protected boolean enabled;
protected boolean active;
}
Now, from my controller
JavaScript
@Override
public ResponseEntity<UserDto> getUser(Integer userId) {
return new ResponseEntity<>(userService.findById(userId), HttpStatus.OK);
}
i get data like this
JavaScript
{
"userId": 141,
"userName": "admin",
"password": "password",
"enabled": true,
"active": false
}
In my case, before send data, i should convert boolean values (enabled, active) to string “Y” or “N”.
JavaScript
{
"userId": 141,
"userName": "admin",
"password": "password",
"enabled": "Y",
"active": "N"
}
How can i do this?
Advertisement
Answer
You can implement a custom serializer. Take a look at the example.
JavaScript
public class UserDto {
protected Integer userId;
protected String userName;
protected String password;
@JsonSerialize(using = BooleanToStringSerializer.class)
protected boolean enabled;
@JsonSerialize(using = BooleanToStringSerializer.class)
protected boolean active;
}
public class BooleanToStringSerializer extends JsonSerializer<Boolean> {
@Override
public void serialize(Boolean tmpBool,
JsonGenerator jsonGenerator,
SerializerProvider serializerProvider)
throws IOException, JsonProcessingException {
jsonGenerator.writeObject(tmpBool ? "Y" : "N");
}
}