Json轉換:讀取Jar包中的json文件
現在操作json的jar 都是用的Gson,
如果需要讀取的json文件不在jar包裏面,則可以這樣獲取到:
//該目錄是以resources目錄爲根目錄
String path = this.getClass().getClassLoader().getResource("json/abc.json").getPath();
//文件內容直接轉爲String類型 String content = FileUtils.readFileToString(new File(path), "UTF-8");
JSONObject obj = JSONObject.parseObject(content)
否則就需要下面這樣獲取:
String jsonStr = "";
//該目錄是以resources目錄爲根目錄
String path = "json/abc.json";
//文件內容直接轉爲String類型
InputStream is = this.getClass().getClassLoader().getResourceAsStream(path);
//舉例:InputStream inputStream = XXXX.class.getClassLoader().getResourceAsStream(path);
BufferedReader in = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null){
buffer.append(line);
}
jsonStr = buffer.toString();
使用Gson獲取內容:
Gson gson = new Gson();
Type type = new TypeToken<Map<String, List<String>>>() {}.getType();
Map<String, List<String>> maps = gson.fromJson(jsonStr, type);
版權聲明:本文爲CSDN博主「就這樣註冊了」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_41369712/article/details/97145476