代码如下
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 "";
}