首页 > 解决方案 > 如何从 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']

标签: javaspring-bootrest

解决方案


谢谢大家的回答,我已经@ResponceBody在我的函数中添加了注释,并从@RequestMapping注释中删除了“生成”部分,我的函数运行良好:

@RequestMapping(value = "/statistic", method = RequestMethod.GET)
@ResponseBody
public GamerData[] getStatistic() {
    //function code
}

推荐阅读