2 回答

TA貢獻1804條經驗 獲得超3個贊
讓我們調用您的文件 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 讀入對象。從那里您可以根據您的用例直接將其作為靜態屬性或作為組件中的屬性引用。

TA貢獻1864條經驗 獲得超2個贊
希望這段代碼對你有用
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 依賴項
添加回答
舉報