Get element from JSON file using getJSONArray() and getJSONObject() in Java

I would like to walk through the json file below and save the part after “coordinates”.

The json file:

{"type": "FeatureCollection","features": [{"type": "Feature","properties": {},"geometry": {"type": "LineString","coordinates": [[4.354282,52.032195],[4.354087,52.032462],[4.353783,52.032962],[4.353579,52.033437],[4.353333,52.034151],[4.352991,52.03545],[4.352517,52.037002],[4.352442,52.037352],[4.352368,52.0378],[4.352336,52.038238],[4.352331,52.039962],[4.352346,52.040706]
    ]
  }
}

] }

I’ve seen code using getJSONArray() and getJSONObject() here and here. This information helped me to select (in my case) the “geometry” tree.

My code so far (test2.geojson is the json file mentioned above):

        String output = new String(Files.readAllBytes(Paths
                .get("C:\Users\****\Desktop\test2.geojson")));

        JSONObject obj = new JSONObject(output);

        JSONArray jsonArray = obj.getJSONArray("features");
        System.out.println(jsonArray);

However, this only rearranges the file and appends the first part to the end of the file.

[{"geometry":{"coordinates":[[4.354282,52.032195],[4.354087,52.032462],[4.353783,52.032962],[4.353579,52.033437],[4.353333,52.034151],[4.352991,52.03545],[4.352517,52.037002],[4.352442,52.037352],[4.352368,52.0378],[4.352336,52.038238],[4.352331,52.039962],[4.352346,52.040706]],"type":"LineString"},"type":"Feature","properties":{}}]

Any solutions to get the desired output of:

[[4.354282,52.032195],[4.354087,52.032462],[4.353783,52.032962],[4.353579,52.033437],[4.353333,52.034151],[4.352991,52.03545],[4.352517,52.037002],[4.352442,52.037352],[4.352368,52.0378],[4.352336,52.038238],[4.352331,52.039962],[4.352346,52.040706]
    ]
  }
}

] }

Thanks in advance. Cheers!

Answer

As “geometry” is a json object {}, “coordinates” is a json array [],

You should be doing

JSONArray jsonArray = obj.getJSONArray("features");
JSONArray resultArray = jsonArray.getJSONObject[0].getJSONObject("geometry").getJSONArray("coordinates")

Leave a Reply

Your email address will not be published. Required fields are marked *