自定义注解
import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author chage
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
public @interface JsonFieldPrefix {
String value() default "";
String splitStr() default "";
boolean trimOrNot() default false;
boolean arrayOrNot() default false;
}
具体处理逻辑
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 org.apache.shiro.util.StringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @Title: JsonFieldPrefix
* @Description: 返回实体类至前端 , 实体类序列化时追加相应的前缀
* 主要用于图片url拼接
* @author: chage
* @date: 2022/3/25 14:09
*/
public class JsonFieldPrefixSerializer extends JsonSerializer<String> implements ContextualSerializer {
private String prefix;
private String splitStr;
private boolean trimOrNot;
private boolean arrayOrNot;
@Override
public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException {
if (!StringUtils.hasText(value)) {
jsonGenerator.writeString(value);
return;
}
if (StringUtils.hasLength(splitStr)) {
String[] valueArr = value.split(splitStr);
List<String> resultList = new ArrayList<>();
for (String valueItem : valueArr) {
if (trimOrNot) {
valueItem = valueItem.trim();
}
resultList.add(prefix + valueItem);
}
if(arrayOrNot){
jsonGenerator.writeArray(resultList.toArray(new String[0]),0,resultList.size());
}else {
jsonGenerator.writeString(String.join(splitStr, resultList));
}
} else {
jsonGenerator.writeString(prefix + value);
}
}
@Override
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
JsonFieldPrefix jsonFieldPrefix = property.getAnnotation(JsonFieldPrefix.class);
if (jsonFieldPrefix != null) {
prefix = jsonFieldPrefix.value();
splitStr = jsonFieldPrefix.splitStr();
trimOrNot = jsonFieldPrefix.trimOrNot();
arrayOrNot = jsonFieldPrefix.arrayOrNot();
}
return this;
}
}
实体类引用方式:
@JsonFieldPrefix(Constant.prefix)