簡體   English   中英

無法在Java中讀取json文件

[英]Cannot read json file in java

我正在使用eclipse讀取jsonfile。 我將jsonfile放在src-> main-> java-> testjson-> jsonfile.json中。 現在,我正在嘗試讀取jsonfile。 但是我的程序無法找到該文件。 我得到的輸出為“ nothing”。 這是我已經實現的代碼:

JsonParser parser = new JSONParser();
try{

Object obj = parser.parse(new FileReader("jsonfile.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");

}

catch(Exception e){
System.out.println("nothing");
}

正如您所說的那樣,您使用Eclipse,我假設您還通過Eclipse運行代碼。 默認情況下,在Eclipse中執行Java程序時的工作目錄是項目的根文件夾。 因此,我建議將jsonfile.json放在項目的根文件夾中,而不是src/main/...

此外,您不應捕獲Exception 捕獲更具體的信息(例如IOExceptionJSONException ,然后輸出異常消息( e.getMessage() ),則可以輕松解決問題。

您在項目內的文件稱為“資源”,它將捆綁在生成的jar -file中。

maven項目中,此類文件駐留在特殊的文件夾resources (例如src/main/resources/testjson/jsonfile.json ),在許多其他項目類型中,這些文件位於java文件的正下方。

因此,您不能使用FileReader讀取它,因為它不是常規文件,而是壓縮在jar文件中。

您所需要做的就是使用this.getClass().getResourceAsStream("/testjson/jsonfile.json")讀取文件。

您的解析器應該能夠從InputStream而不是Reader 如果不是,請使用具有正確編碼的InputStreamReader (JSON文件應為UTF-8,但這取決於...)

碼:

 try (InputStream is = this.getClass().getResourceAsStream("/testjson/jsonfile.json"); ) {
     Object obj = parser.parse(is); 
 } catch (Exception ex) {
     System.out.println("failed to read: "+ex.getMessage());
 }

解析器不支持InputStream代碼:

 try (InputStream is = this.getClass().getResourceAsStream("/testjson/jsonfile.json"); 
     Reader rd = new InputStreamReader(is, "UTF-8"); ) {
     Object obj = parser.parse(rd); 
 } catch (Exception ex) {
     System.out.println("failed to read: "+ex.getMessage());
 }

提供JSON文件的完整路徑,而不是文件名。

如果文件路徑是home / src / main / java / testjson / jsonfile.json

String path = "home/src/main/java/testjson/jsonfile.json";
Object obj = parser.parse(new FileReader(path));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM