一、自定义注解
package com.xxxx.common.sdk.annotation;
import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.xxxx.common.sdk.Serializer.UrlPrefixSerializer;
import java.lang.annotation.*;
/**
* @ClassName UrlPrefix
* @Description 地址前缀
* @email 853632587@qq.com
* @Date 2021/12/21 14:46
* @Version 1.0
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonSerialize(using = UrlPrefixSerializer.class)//注解中引入自定义序列化器
public @interface UrlPrefix {
}
二、序列化
package com.xxxx.common.sdk.Serializer;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.xxxx.common.sdk.annotation.UrlPrefix;
import com.xxxx.common.sdk.constant.BaseConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ObjectUtils;
import java.io.IOException;
import java.util.Arrays;
/**
* @ClassName UrlPrefixSerializer
* @Description 图片前缀处理
* @email 853632587@qq.com
* @Date 2021/12/21 14:28
* @Version 1.0
*/
public class UrlPrefixSerializer extends JsonSerializer<String> implements ContextualSerializer {
private boolean addPrefix;
@Override
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
UrlPrefix addUrlPrefix = property.getAnnotation(UrlPrefix.class);
if (!ObjectUtils.isEmpty(addUrlPrefix)) {
this.addPrefix = true;
}
return this;
}
@Override
public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
if (addPrefix && StringUtils.isNotBlank(value)) {
//如果检测到有自定义注解进行前缀处理
String[] values = value.split(",");
StringBuilder str = new StringBuilder();
Arrays.stream(values).forEach(v -> {
if (str.length() > 0) {
str.append(",");
}
str.append(BaseConstant.FtpConstant.ftpVisitUrl.concat(v).replaceAll("///", "/"));
});
gen.writeString(str.toString());
} else {
gen.writeString(value);
}
}
}
三、指定拦截的字段
@UrlPrefix
@FieldDescrib(name = "求购照片附件" ,desc = "多个图片地址逗号(,)切割")
private String buyImageFiles;