public class NewsPo {
private String id;
private String title;
private String content;
private String path;
}
测试控制器:
@Controller
public class OrderCtl {
@ResponseBody
@RequestMapping("/getNewsList")
public List<NewsPo> getNewsList() {
List<NewsPo> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
NewsPo newsPo = new NewsPo();
newsPo.setId(String.valueOf(i));
newsPo.setPath("www.baidu.com");
list.add(newsPo);
}
return list;
}
}
[
{
"id":"0",
"title":null,
"content":null,
"path":"www.baidu.com"
},
{
"id":"1",
"title":null,
"content":null,
"path":"www.baidu.com"
},
{
"id":"2",
"title":null,
"content":null,
"path":"www.baidu.com"
},
{
"id":"3",
"title":null,
"content":null,
"path":"www.baidu.com"
},
{
"id":"4",
"title":null,
"content":null,
"path":"www.baidu.com"
}
]
要将json中的null转化为""或者0;配置如下代码即可
@Configuration
public class JsonConfig {
private Logger logger = LoggerFactory.getLogger(JsonConfig.class);
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
SerializerProvider serializerProvider = objectMapper.getSerializerProvider();
serializerProvider.setNullValueSerializer(new NullSerializer());
logger.info("注入objectMapper");
return objectMapper;
}
public class NullSerializer extends JsonSerializer<Object> {
@Override
public void serialize(Object value, JsonGenerator jsonGenerator, SerializerProvider provider)
throws IOException {
jsonGenerator.writeString("");
}
}
}
[
{
"id":"0",
"title":"",
"content":"",
"path":"www.baidu.com"
},
{
"id":"1",
"title":"",
"content":"",
"path":"www.baidu.com"
},
{
"id":"2",
"title":"",
"content":"",
"path":"www.baidu.com"
},
{
"id":"3",
"title":"",
"content":"",
"path":"www.baidu.com"
},
{
"id":"4",
"title":"",
"content":"",
"path":"www.baidu.com"
}
]