需要在属性上添加
@JsonSerialize(using = Base64Serializer.class)
@JsonDeserialize(using = Base64Deserializer.class)
private String documentId;
序列化
public class Base64Serializer extends JsonSerializer<String> {
@Override
public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if (!ObjectUtils.isEmpty(s)){
// 对返回的非空字符串进行base64编码
s = Base64.getEncoder().encodeToString(s.getBytes(StandardCharsets.UTF_8));
}
jsonGenerator.writeObject(s);
}
}
反序列化
public class Base64Deserializer extends JsonDeserializer<String> {
private final static Logger logger = LoggerFactory.getLogger(Base64Deserializer.class);
@Override
public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
String text = jsonParser.getText();
return decodeBase64(text);
}
/**
* 对非空的值,尝试base64解码,失败不改变原值
* @param text 待解码的字符串
* @return base64解码后的字符串
*/
public static String decodeBase64(String text){
if (!ObjectUtils.isEmpty(text)){
try {
// 对非空的值,尝试base64解码,失败不改变原值
byte[] txtBytes = Base64.getDecoder().decode(text.getBytes(StandardCharsets.UTF_8));
text = new String(txtBytes, StandardCharsets.UTF_8);
} catch (Exception e){
// 解码失败,text原数返回
logger.error(e.getMessage());
}
}
return text;
}
}