1

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!

1 Answer 1

2

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")
Sign up to request clarification or add additional context in comments.

6 Comments

jsonArray.getJSONObject("geometry") gives the following error. The method getJSONObject(int) in the type JSONArray is not applicable for the arguments (String). I'm using the org.json library.
get the first object from jsonArray first, then apply my code
Thanks for helping. jsonArray.getJSONArray[0] is throwing: getJSONArray cannot be resolved or is not a field.
Are you also using org.json library? Just to be sure.
@Camelaria ops, you should be using jsonArray.getJSONObject(0) ....instead of jsonArray.getJSONArray(0)...my bad but hey you can spot this easily too~
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.