java - 如何从 Spring Boot @Controller 返回 json/xml?
问题描述
我正在尝试从我的控制器的功能返回 JSON/XML。首先我使用@RestController,它工作得很好,但现在我需要更改为@Controller,因为我还将使用其他一些函数并将一些对象传递给我的视图。
@Controller
@RequestMapping("/game")
public class ViewController {
@RequestMapping(value = "/statistic", method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public GamerData[] getStatistic() {
RestTemplate restTemplate = new RestTemplate();
try {
String uri_get_statistic = "http://localhost:8081/statistic/";
ResponseEntity<GamerData[]> response = restTemplate.getForEntity(uri_get_statistic, GamerData[].class);
GamerData[] statisticData = response.getBody();
return statisticData;
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
}
更改为 Controller 后,我收到错误 404 未找到。使用 RestController 我有 json。(GamerData 只是一个具有 2 个简单字段(int 和 String)、setter、getter、consructor 的类)。
更新:我已添加@ResponseBody
到我的功能,但现在我有内部服务器错误
Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter for [class [Lgame.mainservice.mvc.GamerData;] with preset Content-Type 'null']
解决方案
谢谢大家的回答,我已经@ResponceBody
在我的函数中添加了注释,并从@RequestMapping
注释中删除了“生成”部分,我的函数运行良好:
@RequestMapping(value = "/statistic", method = RequestMethod.GET)
@ResponseBody
public GamerData[] getStatistic() {
//function code
}
推荐阅读
- ios - 当iOS react native app在后台收到推送通知时不会调用onNotification
- sql-server - SQL 和数据开头的空行
- javascript - 如何使用 jquery 和 css 更改点击动画的背景图像
- go - Go build tdlib 非常慢的重建
- java - 4种不同车辆的预订系统
- python - EGL 驱动程序消息(错误) eglQueryDeviceAttribEXT:属性错误
- node.js - Postgres ECONNREFUSED 在 Docker Compose 上使用 NodeJS
- python - 以编程方式从嵌套列表中检索元素
- java - java数组可以有多少维?每个维度的大小?
- sass - 有没有办法在 SASS/SCSS 中包含、要求或路由