多个场景@RequestMapping与Accept或ResponseEntity一起生成JSONXML

多个场景@RequestMapping与Accept或ResponseEntity一起生成JSONXML,第1张

多个场景@RequestMapping与Accept或ResponseEntity一起生成JSON / XML

使用Accept标头真的很容易从REST服务中获取json或xml格式。

这是我的控制器,看一下产生部分。

@RequestMapping(value = "properties", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}, method = RequestMethod.GET)    public UIProperty getProperties() {        return uiProperty;    }

为了使用REST服务,我们可以使用下面的代码,其中标头可以是MediaType.APPLICATION_JSON_VALUE或MediaType.APPLICATION_XML_VALUE

HttpHeaders headers = new HttpHeaders();headers.add("Accept", header);HttpEntity entity = new HttpEntity(headers);RestTemplate restTemplate = new RestTemplate();ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/properties", HttpMethod.GET, entity,String.class);return response.getBody();

编辑01:

为了配合使用

application/xml
,请添加此依赖项

<dependency>    <groupId>com.fasterxml.jackson.dataformat</groupId>    <artifactId>jackson-dataformat-xml</artifactId></dependency>


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5018626.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-14
下一篇2022-11-15

发表评论

登录后才能评论

评论列表(0条)

    保存