Spring-Returning json with @ResponseBody when the Accept header is */* throws HttpMediaTypeNotAcceptableException

后端 未结 3 827
情深已故
情深已故 2021-01-07 02:00

I\'m using spring 3.0.0.

I have an endpoint that returns an object that I want to be serialized to JSON. When the request comes in with Accept: application/json, it

3条回答
  •  时光取名叫无心
    2021-01-07 02:51

    From everything I've gathered today there are 2 options to get around this issue.

    1. Write a BeanPostProcessor that will update the supported mime types on the MappingJacksonConverter to accept /. (using the supportedMimeTypes property just doesn't work....see https://jira.springsource.org/browse/SPR-6214

    2. Here's the solution I'm going with for now. It's not pretty, but neither is setting an Accept header of / when you are expecting application/json everytime. I ended up adding the ServletResponse object to my method and using the old school way of writing directly to the output stream to bypass the message converters and get my response returned.


    @RequestMapping(value = "/v1/endpoint", method = RequestMethod.POST)
    public void runEndpoint(@RequestBody String jsonData,
    ServletResponse response) {
    
        ObjectMapper mapper = new ObjectMapper();
        EndpointRequest opRequest = null;
        EnpointResponse opResponse = null;
        StringWriter sw = new StringWriter();
    
        try {
    
            opRequest = mapper.readValue(jsonData, EndpointRequest.class);
    
            opResponse = ...do stff...
    
            mapper = new ObjectMapper();
    
            mapper.writeValue(sw, opResponse);
    
            response.setContentType("application/json");
            response.getOutputStream().write(sw.toString().getBytes());
    
            } catch (JsonParseException e) {
            handleException(opResponse, e, response);
            } catch (JsonMappingException e) {
            handleException(opResponse, e, response);
            } catch (IOException e) {
            handleException(opResponse, e, response);
        }
    }
    

    If you have anything more elegant, I'd love to see it!

提交回复
热议问题