简体   繁体   English

我如何以某种方式“将” json文件“存储”在Spring-Boot程序中,以便我的Web应用程序随后读取此json

[英]How can I somehow “store” a json file in a Spring-Boot program so my web app then reads this json

Basically, I'm writing my first Spring-Boot program, and I have to get a list of products stored on a JSON file to display each product using VueJS (I know how to use Vue, I just need to get the JSON data somewhere in the webpage or smth) 基本上,我正在编写我的第一个Spring-Boot程序,我必须获取存储在JSON文件中的产品列表,才能使用VueJS显示每个产品(我知道如何使用Vue,我只需要在某个地方获取JSON数据在网页或smth中)

I spent last 3'5 hours looking at tutorials about consuming JSON's and POST stuff and none helped. 我花了最后3到5个小时来查看有关使用JSON和POST内容的教程,但没有帮助。

Lets call your file config.json. 让我们调用您的文件config.json。

In a typical maven project, keep your file at 在典型的Maven项目中,将文件保存在

src/main/resources/config.json

In your code, read it like 在您的代码中,像这样阅读

    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);
    }

After this, use Jackson or GSON to read the json into an object. 之后,使用Jackson或GSON将json读入对象。 From there you can either reference it directly as a static attribute or as an attribute in component as per your use case. 在这里,您可以根据用例将其直接引用为静态属性或组件中的属性。

Hope this code will work for you 希望这段代码对您有用

public class JsonReader{
    public static void readFromJson() throws Exception {
        InputStream inStream = JsonReader.class.getResourceAsStream("/" + "your_config_file.json");
        Map<String, String> keyValueMap =
                new ObjectMapper().readValue(inStream, new TypeReference<Map<String, String>>() {});
        inStream.close();
    }
}

You might need to add the maven dependency for ObjectMapper() 您可能需要为ObjectMapper()添加Maven依赖项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM