简体   繁体   English

为什么在将json映射到Java bean期间,Spring MVC为什么将参数[“”]转换为[null]?

[英]Why Spring MVC transform parameter [“”] to [null] during mapping json to java bean?

I want to know why spring mvc transform [""] to [null] when I use PostMan to test my API. 我想知道为什么当我使用PostMan测试我的API时spring mvc将[“”]转换为[null]。 here is my controller: 这是我的控制器:

    @RequestMapping(value = "", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody ResponseEntity<Object> participateRstActivities(
        HttpServletRequest request, @RequestBody RstActivityFrom rstForm)
        throws ServiceException {
          log.info("list size:{}, frist object:{}",rstForm.getRestaurant_ids().size(), rstForm.getRestaurant_ids().get(0));
        }

here is my java bean: 这是我的Java Bean:

public class RstActivityFrom {

    private List<Integer> restaurant_ids;
    private int activity_id;
    // omit getter & setter
}

here is my request body when I use postman to test my api: 这是我使用邮递员测试api时的请求正文:

{
 "restaurant_ids":[""],
 "activity_id":119129
}

and the log in controller print : list size:1, frist object:null. 并在控制器中输入print:list size:1,第一个object:null。

this problem makes me feel confuse, I want to know why. 这个问题让我感到困惑,我想知道为什么。 Thanks 谢谢

Since restaurant_ids is a List and not String, Change your JSON for restaurant_ids: 由于restaurant_ids是一个List而不是String,因此请更改restaurant_ids的JSON:

{
 "restaurant_ids":[],
 "activity_id":119129
}

If you don't want to allow an empty String value for objects mapped from your JSON, you can look into setting the Jackson's ObjectMapper Features as described here: 如果您不想为从JSON映射的对象允许使用空String值,则可以按照以下说明研究设置Jackson的ObjectMapper功能:

https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html

The Java API for Jackson's DeserializationConfig.Feature(s) can be found here: 可以在以下位置找到用于Jackson的DeserializationConfig.Feature(s)的Java API:

http://fasterxml.github.io/jackson-core/javadoc/1.9/org/codehaus/jackson/map/DeserializationConfig.Feature.html http://fasterxml.github.io/jackson-core/javadoc/1.9/org/codehaus/jackson/map/DeserializationConfig.Feature.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM