MappingJacksonJsonView return top-level json object

后端 未结 3 1543
粉色の甜心
粉色の甜心 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 02:59

    What's happening is Spring MVC is taking the ModelAndView and serializing it to JSON. Since a ModelAndView just looks like a map, and in this case, you only have one entry in the map with a key name of myObject, that's what the JSON response looks at. In order to get just your object, you need to return just your object instead of a ModelAndView and let Jackson serialize your object to JSON.

    Rather than returning a ModelAndView, return a MyObject and annotate the method with @ResponseBody, so your controller method becomes

    @RequestMapping(value="/id/{id}", method=RequestMethod.GET, produces="application/json")
    public @ResponeBody MyObject getById(@PathVariable (value="id") String id) {
        return doGetById(id);
    }
    

提交回复
热议问题