隨筆,jackson自定義輸出格式的三種方法

場景一: 數據庫存儲性別爲1男,2女,頁面輸出要展現男 或 女數據庫

使用@JsonSerialize註解。bash

@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");
        }
    }
}
複製代碼

場景二: 某金融項目中,須要爲全部金額添加單位app

//數據類
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時返回""ide

//自定義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));
複製代碼

返回目錄

相關文章
相關標籤/搜索