的Maven依赖关系
基本上,我正在编写我的第一个弹簧启动程序,我必须获取存储在JSON文件上的产品列表以使用VUEJS显示每个产品(我知道如何使用vue,我只需要在网页或smth中的某个地方获取JSON数据(
我花了3'5小时来查看有关消费JSON和发布内容的教程,没有帮助。
让我们调用您的文件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((