![](/img/trans.png)
[英]How can i avoid the queries of my spring-boot with hibernate app will be written to console or file?
[英]How can I somehow “store” a json file in a Spring-Boot program so my web app then reads this 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读入对象。 在这里,您可以根据用例将其直接引用为静态属性或组件中的属性。
希望这段代码对您有用
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();
}
}
您可能需要为ObjectMapper()添加Maven依赖项
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.