2017-05-26 248 views
0

我寫了一個程序,讀取一個簡單的JSON文件:閱讀JSON文件

public static void main(String[] args) { 
    JSONParser parser = new JSONParser(); 
    try { 
     JSONArray a = (JSONArray) parser.parse(new FileReader("C:/Users/Zonoid/Desktop/EQ.json")); 
     for (Object o : a) 
     { 
      JSONObject obj = (JSONObject) o; 
      String city = (String) obj.get("CITY"); 
      System.out.println("City : " + city); 
      String loc = (String) obj.get("LOCATION"); 
      System.out.println("Location : " + loc); 
      long el = (Long) obj.get("E_LEVEL"); 
      System.out.println("Emergency Level : " + el); 
      long depth = (Long) obj.get("DEPTH"); 
      System.out.println("Depth : " + depth); 
      long i = (Long) obj.get("INTENSITY"); 
      System.out.println("Intensity :"+i); 
      System.out.println("\n"); 
     } 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 
} 

與我的JSON文件的存在:

[{"CITY":"MUMBAI","LOCATION":"a" ,"E_LEVEL": 6,"DEPTH":10,"INTENSITY":5}, 
{"CITY":"MUMBAI","LOCATION":"b" ,"E_LEVEL": 8,"DEPTH":20,"INTENSITY":4}, 
{"CITY":"MUMBAI","LOCATION":"c" ,"E_LEVEL": 3,"DEPTH":13,"INTENSITY":5}, 
{"CITY":"MUMBAI","LOCATION":"d" ,"E_LEVEL": 6,"DEPTH":12,"INTENSITY":4},] 

我工作的一個項目是處理地震警報並希望閱讀他們的JSON文件,但是我無法將它們導入到JSON數組中。該文件我想進口看起來像這樣:

{ 
    "type": "FeatureCollection", 
    "metadata": { 
    "generated": 1488472809000, 
    "url": "https:\/\/earthquake.usgs.gov\/earthquakes\/feed\/v1.0\/summary\/significant_week.geojson", 
    "title": "USGS Significant Earthquakes, Past Week", 
    "status": 200, 
    "api": "1.5.4", 
    "count": 2 
    }, 
    "features": [ 
    { 
     "type": "Feature", 
     "properties": { 
     "mag": 5.5, 
     "place": "42km WSW of Anchor Point, Alaska", 
     "time": 1488420690658,.... 

請告訴一下修改的話。

+0

你發佈的代碼有什麼問題? –

+0

它給出了錯誤org.json.simple.JSONObject不能轉換爲org.json.simple.JSONArray \t at practice.json.main(json.java:17) – apoorv

+0

我現在看到。你需要改變你的json文件。 json文件包含一個對象(它以{開始並以}結尾),你希望它成爲一個對象數組(以[{開始並以}結尾]開頭 –

回答

2

如果您只想從功能中讀取數據,首先需要將整個文件作爲對象讀取。然後你可以通過以下方式讀取陣列部分:

Object object = parser.parse(new FileReader("C:/Users/Zonoid/Desktop/EQ.json")); 
JSONObject jasonObject = (JSONObject) object; 
JSONArray features = (JSONArray) jasonObject.get("features"); 
+0

好吧,我的錯誤是直接使用JSONObject和parser.parse而不進行轉換。謝謝您的幫助 – apoorv