SpringBoot Controllerがjsonに返すnullを空白列または0に置き換える
3303 ワード
public class NewsPo {
private String id;
private String title;
private String content;
private String path;
}
テストコントローラ:
@Controller
public class OrderCtl {
@ResponseBody
@RequestMapping("/getNewsList")
public List getNewsList() {
List 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
[
{
"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"
}
]