一、对字符串去除空格,如果字符串为null,则返回""
/** * 对字符串去除空格,如果字符串为null,则返回"" * @param str :输入字符串 * @return :trim后结果 */ public static String trim(String str) { if (null == str) { return ""; } return str.trim(); }
二、自定义一个objectmapper
@Configuration class JacksonConfig { @Bean @Primary @ConditionalOnMissingBean(ObjectMapper.class) public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper objectMapper = builder.createXmlMapper(false).build(); SerializerProvider serializerProvider = objectMapper.getSerializerProvider(); serializerProvider.setNullValueSerializer(new JsonSerializer<Object>() { @Override public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeString(""); } }); return objectMapper; } }注意但是这个方法会把对象为空,list ,map ,枚举 为 null的情况下也转成 空字符串,这是个弊端,根据需求而用吧。