jackson 空值转成空串输出

代码如下

public class Serializers extends JsonSerializer<Object> {
  public static final JsonSerializer<Object> EMPTY_STRING_SERIALIZER_INSTANCE = new EmptyStringSerializer();

  public Serializers() {}

  @Override
  public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
      throws IOException, JsonProcessingException {
    jsonGenerator.writeString("");
  }

  private static class EmptyStringSerializer extends JsonSerializer<Object> {
    public EmptyStringSerializer() {}

    @Override
    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
        throws IOException, JsonProcessingException {
      jsonGenerator.writeString("");
    }
  }
}
/**
* jackson 空值转换成空字符串输出
* @Author jrx
* @Date 2018/11/27 16:19
**/
public class CustomSerializerProvider extends DefaultSerializerProvider {

  public CustomSerializerProvider() {
    super();
  }

  public CustomSerializerProvider(CustomSerializerProvider provider, SerializationConfig config,
                                  SerializerFactory jsf) {
    super(provider, config, jsf);
  }

  @Override
  public CustomSerializerProvider createInstance(SerializationConfig config, SerializerFactory jsf) {
    return new CustomSerializerProvider(this, config, jsf);
  }

  @Override
  public JsonSerializer<Object> findNullValueSerializer(BeanProperty property) throws JsonMappingException {
//    if (property.getType().getRawClass().equals(String.class))
//      return Serializers.EMPTY_STRING_SERIALIZER_INSTANCE;
//    else
//      return super.findNullValueSerializer(property);
    return Serializers.EMPTY_STRING_SERIALIZER_INSTANCE;
  }
}

使用方式如下

Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder = Jackson2ObjectMapperBuilder.json();
jackson2ObjectMapperBuilder.simpleDateFormat("yyyy-MM-dd HH:mm:ss");
jackson2ObjectMapperBuilder.timeZone("GMT+08:00");
ObjectMapper nullMapper = jackson2ObjectMapperBuilder.build();
nullMapper.setSerializerProvider(new CustomSerializerProvider());
try {
  return nullMapper.writeValueAsString(qb.
      map(vJcptQbml -> Return.of(SystemStatus.SUCCESS, vJcptQbml))
      .orElseGet(() -> Return.of(SystemStatus.FAILURE)));
} catch (JsonProcessingException e) {
  log.error("", e);
  //never happen
  return "";
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值