简体   繁体   English

在Java中读取具有多个对象的json文件

[英]Reading json file with multiple objects in java

I have written a program that reads a simple json file: 我写了一个程序,读取一个简单的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();
    }
}

with my json file being: 我的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},]

I am working on a project that deals with earthquake alerts and want to read their JSON files however I cannot import them in JSON Array. 我正在一个处理地震警报的项目,并且想读取其JSON文件,但是无法将其导入JSON数组中。 The file I want to import looks like this: 我要导入的文件如下所示:

{
  "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,....

Please tell what changes should be made. 请告诉我们应该进行哪些更改。

If you are trying to read from features only, first you need to read the whole file as an object. 如果仅尝试读取功能,则首先需要将整个文件作为对象读取。 Then you can, read the array part in the following way: 然后,您可以通过以下方式读取数组部分:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM