注入
@Bean
@Primary
@ConditionalOnMissingBean({ObjectMapper.class})
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
// 定义 不为空,才能进行序列化
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// 添加 自定义 项目注解内省器
objectMapper.setAnnotationIntrospector(new ProjectJacksonAnnotationIntrospector());
return objectMapper;
}
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
/**
* 功能描述: 字典序列化 <br/>
*/
public class DictSerializer extends StdSerializer<Object> {
/** 字典类型 */
private final String type;
/** 分隔符 */
private final String separator;
public DictSerializer(String type, String separator) {
super(Object.class);
this.type = type;
this.separator = separator;
}
@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
// gen.writeObject(this.getLabel(value.toString()));
provider.defaultSerializeValue(value, gen);
gen.writeStringField(gen.getOutputContext().getCurrentName().concat("Text"), "111");
}
/**
* 功能描述: 核心逻辑 <br/>
* 将码值 转换成 显示对象
* @param code 数据内容
* @return "com.cah.project.core.domain.out.DictData"
*/
private String getLabel(String code) {
return code;
}
}
/**
* 功能描述: 自定义项目内神器 <br/>
*/
public class ProjectJacksonAnnotationIntrospector extends JacksonAnnotationIntrospector {
public ProjectJacksonAnnotationIntrospector() {}
@Override
public Object findSerializer(Annotated a) {
// 如果是字典注解
Dict dict = _findAnnotation(a, Dict.class);
if(dict != null) {
return new DictSerializer(dict.type(), dict.separator());
}
// 其他扩展。。。
return super.findSerializer(a);
}
}
网友评论