Skip to content
Advertisement

Convert fields before sending to the page

I have a user dto class and i need to convert some of its properties before send it to frontend.

UsedDto class

public class UserDto {
    protected Integer userId;
    protected String userName;
    protected String password;
    protected boolean enabled;
    protected boolean active;
}

Now, from my controller

@Override
public ResponseEntity<UserDto> getUser(Integer userId) {
    return new ResponseEntity<>(userService.findById(userId), HttpStatus.OK);
}

i get data like this

{
"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”.

{
"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.

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");
    }
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement