java - 我怎样才能以某种方式在 Spring-Boot 程序中“存储”一个 json 文件,以便我的 web 应用程序读取这个 json
问题描述
基本上,我正在编写我的第一个 Spring-Boot 程序,我必须获取存储在 JSON 文件中的产品列表,以使用 VueJS 显示每个产品(我知道如何使用 Vue,我只需要在某处获取 JSON 数据在网页或smth)
我花了 3'5 小时查看有关使用 JSON 和 POST 内容的教程,但没有任何帮助。
解决方案
让我们调用您的文件 config.json。
在典型的 Maven 项目中,将文件保存在
src/main/resources/config.json
在您的代码中,像这样阅读
try {
ClassPathResource configFile = new ClassPathResource("config.json");
String json = IOUtils.toString(configFile.getInputStream(), Charset.forName(Util.UTF_8));
} catch (IOException e) {
String errMsg = "unexpected error while reading config file";
logger.error(errMsg, e);
throw new Exception(e);
}
之后,使用 Jackson 或 GSON 将 json 读入对象。从那里您可以根据您的用例直接将其作为静态属性或组件中的属性引用。
推荐阅读
- sql - SQL 计算所有不同的总计和小计
- reactjs - 如何让 `react-bootstrap` 和 `react-hook-form` 发挥得很好?
- javascript - 当用户专注于输入时如何推荐文本
- java - 如何在 Mirth Connect 中读取数据库并将结果转换为 HL7 文件
- elasticsearch - ElasticSearch v5.6.16 throws XContentParseException failed to parse field [version] error while using Java High Level REST Client
- vb.net - 用于检测 PDF 中文本页面更改的字符串拆分
- android - 在运行 Android 11 的摩托罗拉设备上打开键盘时应用程序崩溃
- python - 在线程中取消选中 QPushButton
- css - 手写笔:如何在保存导入文件后重新编译
- r - r - for 循环按所有行比较 2 个数据帧