阅读 37

随笔,jackson自定义输出格式的三种方法

场景一: 数据库存储性别为1男,2女,页面输出要展示男 或 女

使用@JsonSerialize注解。

@Data
public class Human {

    private String name;

    private Integer age;

    @JsonSerialize(using = SexSerializer.class)
    private Integer sex;

}

public class SexSerializer extends StdSerializer<Integer> {

    private SexSerializer() {
        super(Integer.class);
    }

    @Override
    public void serialize(Integer value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if(value==1){
            gen.writeString("male");
        }else if(value==2){
            gen.writeString("female");
        }else {
            gen.writeString("unKnow");
        }
    }
}
复制代码

场景二: 某金融项目中,需要为所有金额添加单位

//数据类
public class Money {

    private BigDecimal value;

}
//序列号类
public class MoneySerializer extends StdSerializer<BigDecimal> {
    
    public MoneySerializer() {
        super(BigDecimal.class);
    }

    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeString("¥"+value);
    }
}
//将序列化配置添加进SimpleModule,在将SimpleModule注册进ObjectMapper
//这样全局都可以使用
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(BigDecimal.class,new MoneySerializer());
mapper.registerModule(module);
复制代码

场景三:字符串为null时返回""

//自定义String null值的序列化对象
public class NullStringSerializer extends StdSerializer<Object> {

    public NullStringSerializer() {
        super(Object.class);
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeString("");
    }
}

//将自定义null值序列号对象注册进序列化装饰器
@Component
public class CustomNullSerializerModifier extends BeanSerializerModifier {

    @Autowired
    private NullStringSerializer nullStringSerializer;

    @Override
    public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
        for (BeanPropertyWriter writer : beanProperties) {
            Class<?> rawClass = writer.getType().getRawClass();
            if(rawClass.isAssignableFrom(String.class)){
                writer.assignNullSerializer(nullStringSerializer);
            }
        }
        return beanProperties;
    }
}
//将装饰器注册进ObjectMapper对象,这样就可以将全局的null String改为""
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializerFactory(objectMapper.getSerializerFactory().withSerializerModifier(nullSerializerModifier));
复制代码

返回目录

关注下面的标签,发现更多相似文章
评论