首页 > 解决方案 > Spring 请求返回 json 或 xml 响应

问题描述

我有一个 Spring 请求映射,我想默认返回 XML,或者如果在请求标头中指定了 JSON。这是一些代码:

请求映射

@RequestMapping(value = "/batch/{progName}", method = RequestMethod.GET, produces = "application/xml)
    public ResponseEntity<JobResults> processTestObject(@PathVariable("progName") String progName,
                                                        @RequestHeader("Content-Type") String contentType) throws Exception {
        HttpHeaders responseHeaders = MccControllerUtils.createCacheDisabledHeaders();
        if(contentType.equals("application/json")) {
            responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        }
        LOGGER.info("Running batch program " + progName);
        JobResults response = batchService.processProgName(progName);
        return new ResponseEntity<JobResults>(response, responseHeaders, HttpStatus.OK);
    }

我想要的是:

默认情况下从端点返回 XML,如果在请求中指定则返回 JSON

编辑

截至目前,当Postman400 Bad Request中没有Accept或发送时,请求返回。Content-Type为了检索所需的响应,我必须指定AcceptandContent-Typeapplication/xml

 @RequestMapping(value = "/batch/{progName}", method = RequestMethod.GET)
    public ResponseEntity<JobResults> processTestObject(@PathVariable("progName") String progName,
                                                        @RequestHeader("Content-Type") MediaType contentType) throws Exception {
        HttpHeaders responseHeaders = MccControllerUtils.createCacheDisabledHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_XML);
        if(!contentType.toString().equals("*/*")) {
            responseHeaders.setContentType(contentType);
        }
        LOGGER.info("Running batch program " + progName);
        JobResults response = batchService.processProgName(progName);
        return new ResponseEntity<JobResults>(response, responseHeaders, HttpStatus.OK);
    }

标签: jsonxmlspringhttp

解决方案


您的示例仍然Content-Type取自应在的请求Accept。其次,确保您的 JobResults 对象可被 json marshaller 和 xml marshaller 序列化。第三,如果你想要特定的行为是请求 json,你应该检查那个特定的媒体类型,而不是像"*/*".

控制器:

@RequestMapping(value = "/batch/{progName}", method = RequestMethod.GET)
public ResponseEntity<JobResults> processTestObject(@PathVariable("progName") String progName,
                                                    @RequestHeader("Accept") MediaType accept) throws Exception {
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.APPLICATION_XML);
    if(!accept.toString().equals("*/*")) {
        responseHeaders.setContentType(accept);
    }
    JobResults response = new JobResults("23423", "result");
    return new ResponseEntity<JobResults>(response, responseHeaders, HttpStatus.OK);
}

一些响应对象,但已注释。

@XmlRootElement
public class JobResults {
    String id;
    String name;

    public JobResults(String id, String name) {
        this.id = id;
        this.name = name;
    }

    ....
}

application/json当通过标头请求时,上面的代码给了我Accept


推荐阅读