JSON parameter in spring MVC controller

后端 未结 5 557
感动是毒
感动是毒 2020-11-27 04:51

I have

@RequestMapping(method = RequestMethod.GET)
@ResponseBody
SessionInfo register(UserProfile profileJson){
  ...
}

I pass profileJson

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 05:25

    You can create your own Converter and let Spring use it automatically where appropriate:

    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.springframework.core.convert.converter.Converter;
    import org.springframework.stereotype.Component;
    
    @Component
    class JsonToUserProfileConverter implements Converter {
    
        private final ObjectMapper jsonMapper = new ObjectMapper();
    
        public UserProfile convert(String source) {
            return jsonMapper.readValue(source, UserProfile.class);
        }
    }
    

    As you can see in the following controller method nothing special is needed:

    @GetMapping
    @ResponseBody
    public SessionInfo register(@RequestParam UserProfile userProfile)  {
      ...
    }
    

    Spring picks up the converter automatically if you're using component scanning and annotate the converter class with @Component.

    Learn more about Spring Converter and type conversions in Spring MVC.

提交回复
热议问题