在测试移动端接口的时候,手机端开发的人要求我们把返回对象null转成空字符串,觉得页面显示null不美观。虽然我让他们在手机端判断一下就好,不过他们很不情愿的样子,实际上就是懒。算了,我就上网查找了一下资料
import java.io.IOException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
/**
* null返回空字符串
* @author 戴旌旗
*
*/
@Configuration
public 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;
}
}
之后所有的null对象都会转为空字符串。
但是手机端那边又不愿意了,他们说数组和对象不要返回空字符串,要么返回[]和{},要么返回null。
原来这个方法如此霸道,怎么想都不合适啊,我想在这个方法基础上判断原来对象的类型,只有String才返回空字符串,可惜这个方法十分不完善,根本无法判断对象的类型,null值就是null值。我只好找别的方法。一通寻找后,找到了合适的代码
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter{
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
converter.setFeatures(SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty,//字符串null返回空字符串
SerializerFeature.WriteNullBooleanAsFalse,
SerializerFeature.PrettyFormat);
converters.add(converter);
}
}
这个方法就很合适,不仅可以针对性地把null字符串转为空字符串,还有很多其他的功能,具体详情看SerializerFeature。
然后正当我以为大功告成的时候,手机端的开发又告诉我时间戳和返回参数首字母大写失效了(手机端接口极不规范,参数应该首字母小写的),这对应着@JsonFormat和@JsonProperty注解。仔细看看这两个注解都属于com.fasterxml.jackson,而
WebMvcConfigurerAdapter是属于com.alibaba.fastjson的。这让我十分郁闷,这两个都失效那我岂不是就不能用转化器了。那移动端的需求我就无法满足了,或者只能很low的一个个判断字符串把null转为"",幸好我找到了替代品,@JSONField。
@JSONField(format="yyyy-MM-dd HH:mm:ss")可以代替@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@JSONField(name="T3")可以代替@JsonProperty(value="T3")
保险起见我把两个注解都写上了,方便以后随时改换体系。
最近看到了jackson转换不同类型的博客