首页 > 解决方案 > 我怎样才能以某种方式在 Spring-Boot 程序中“存储”一个 json 文件,以便我的 web 应用程序读取这个 json

问题描述

基本上,我正在编写我的第一个 Spring-Boot 程序,我必须获取存储在 JSON 文件中的产品列表,以使用 VueJS 显示每个产品(我知道如何使用 Vue,我只需要在某处获取 JSON 数据在网页或smth)

我花了 3'5 小时查看有关使用 JSON 和 POST 内容的教程,但没有任何帮助。

标签: javajsonspring-boot

解决方案


让我们调用您的文件 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 或 GS​​ON 将 json 读入对象。从那里您可以根据您的用例直接将其作为静态属性或组件中的属性引用。


推荐阅读