You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot REST API 返回JSON文件的存储位置及相关实现疑问

JSON文件不需要放在templates目录,templates目录是专门给Thymeleaf等模板引擎存放动态渲染模板用的,仅处理HTML类模板返回逻辑,静态JSON文件不属于模板文件。

存放位置

静态JSON文件统一存放在Spring Boot默认静态资源目录 src/main/resources/static 下即可,该目录下的所有资源会被自动映射为可直接访问的静态路径。

两种实现方式

方式1:无控制器直接访问

直接将你需要返回的JSON文件(例如demo.json)放入static目录,无需编写任何控制器代码,直接访问域名/demo.json即可拿到对应的JSON文件内容,响应头会自动携带application/json类型。

方式2:控制器封装返回(适合需要加业务逻辑的场景)

如果需要在返回JSON前做权限校验、动态选择JSON文件等业务逻辑,可以通过控制器读取静态JSON文件后返回,代码示例如下:

import org.springframework.core.io.ClassPathResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.nio.file.Files;

@RestController
public class JsonController {

    @GetMapping("/demo")
    public ResponseEntity<String> getDemoJson() throws IOException {
        // 读取static目录下的demo.json
        ClassPathResource jsonFile = new ClassPathResource("static/demo.json");
        String content = Files.readString(jsonFile.getFile().toPath());
        return ResponseEntity.ok()
                .header("Content-Type", "application/json")
                .body(content);
    }
}

扩展:动态生成JSON返回(REST API常用写法)

如果你不需要返回固定静态JSON文件,而是需要接口动态生成JSON内容,不需要额外创建JSON文件,直接返回Java对象即可,Spring Boot内置的Jackson序列化工具会自动将对象转为JSON格式响应,示例如下:

@RestController
public class UserController {

    @GetMapping("/user/info")
    public UserInfo getUserInfo() {
        UserInfo info = new UserInfo();
        info.setId(1001);
        info.setUsername("test");
        info.setEmail("test@example.com");
        return info;
    }

    public static class UserInfo {
        private Integer id;
        private String username;
        private String email;
        // 此处省略getter、setter方法
    }
}

注意事项

  • 不要将静态JSON文件放入templates目录,该目录不会被静态资源扫描器识别,无法直接访问
  • 如果需要自定义静态资源存放路径,可以在application配置文件中修改spring.web.resources.static-locations配置项
  • 开发REST API优先使用@RestController注解,无需额外添加@ResponseBody注解即可自动返回JSON格式数据

内容的提问来源于stack exchange,提问作者Luk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 10:24:01