我有一個用戶 dto 類,我需要在將其發送到前端之前轉換它的一些屬性。
使用Dto類
public class UserDto {
protected Integer userId;
protected String userName;
protected String password;
protected boolean enabled;
protected boolean active;
}
現在,從我的控制器
@Override
public ResponseEntity<UserDto> getUser(Integer userId) {
return new ResponseEntity<>(userService.findById(userId), HttpStatus.OK);
}
我得到這樣的資料
{
"userId": 141,
"userName": "admin",
"password": "password",
"enabled": true,
"active": false
}
就我而言,在發送資料之前,我應該將布林值(啟用、活動)轉換為字串“Y”或“N”。
{
"userId": 141,
"userName": "admin",
"password": "password",
"enabled": "Y",
"active": "N"
}
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
您可以實作自定義序列化程式。看看這個例子。
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");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/435141.html
上一篇:是什么導致Spring在使用AnnotationConfigApplicationContext時無法加載配置類?
