MappingJacksonJsonView return top-level json object

后端 未结 3 1545
粉色の甜心
粉色の甜心 2021-01-03 02:23

I converted to controller to use ContentNegotiatingViewResolver instead of MessageConverters to support multiple output types. With json, I am using MappingJacksonJsonView:

3条回答
  •  旧巷少年郎
    2021-01-03 03:03

    You should be able to remove the outer node by using MappingJacksonJsonView.setExtractValueFromSingleKeyModel(true):

    Set whether to serialize models containing a single attribute as a map or whether to extract the single value from the model and serialize it directly.

    The effect of setting this flag is similar to using MappingJacksonHttpMessageConverter with an @ResponseBody request-handling method.

    For example:

    private final MappingJacksonJsonView view = new MappingJacksonJsonView();
    
    public MyController() {
         view.setExtractValueFromSingleKeyModel(true);
    }
    
    @RequestMapping(value = "/id/{id}", method = RequestMethod.GET)
    public ModelAndView getById(@PathVariable (value="id") String id) {
        MyObject ret = doGetById(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setView(this.view);
        modelAndView.addObject("myObject", ret);
        return modelAndView;
    }
    

    This should also work if you prefer to do it via configuration:

    
        
    
    

提交回复
热议问题