I have a (Geo)JSON File with doubles (they represent coordinates). How can I change these numbers? Say I want to add 100.0, 20.0 to all of the coordinates so that [10.0, 50.0] becomes [110.0, 70.0]. I tried using nashorn in java but since I don't know how to use Javascript it didn't work. I would be happy for a java solution but other solutions are ok as well. So what I tried:
public static void geojsonparser() throws JsonParseException, JsonMappingException, IOException, ScriptException{
InputStream s1 = new FileInputStream( PATH+"triangle0tolerance2.geojson" );
FeatureCollection featureCollection =
new ObjectMapper().readValue(s1, FeatureCollection.class);
ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine engine = engineManager.getEngineByName("nashorn");
engine.eval("function sum(a, b) { return a + b; }");
engine.eval("s1.coordinates.forEach(function(coords){ var feat={'type':'Polygon','coordinates':coords};console.log(JSON.stringify(feat));});");
System.out.println(engine.eval("sum(1, 2);"));
}
and I got the error: Exception in thread "main" javax.script.ScriptException: ReferenceError: "s1" is not defined in <eval> at line number 1
As I mentioned: I would prefer a java solution without javascript :)
Update to Yazans comment: My file looks like this:
{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "DN": 255 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 0.0, 0.0 ], [ 0.0, 12.0 ], [ 12.0, 12.0 ], [ 12.0, 0.0 ], [ 0.0, 0.0 ] ], [ [ 4.0, 4.0 ], [ 5.0, 4.0 ], [ 9.0, 9.0 ], [ 4.0, 9.0 ], [ 4.0, 4.0 ] ] ] } },
{ "type": "Feature", "properties": { "DN": 0 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 4.0, 4.0 ], [ 4.0, 9.0 ], [ 9.0, 9.0 ], [ 9.0, 8.0 ], [ 4.0, 4.0 ] ] ] } }
]
}
And I tried to do as you said. Here my Code:
public static void geojsonparser2() throws JsonParseException,
JsonMappingException, IOException, ParseException {
InputStream s1 = new FileInputStream(PATH
+ "triangle0tolerance2.geojson");
// read the json file
FileReader reader = new FileReader(PATH + "triangle0tolerance2.geojson");
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
// get a String from the JSON object
String firstName = (String) jsonObject.get("type");
System.out.println("The type is: " + firstName);
// get an array from the JSON object
JSONArray lang = (JSONArray) jsonObject.get("coordinates");
// take the elements of the json array
for (int i = 0; i < lang.size(); i++) { //NullPointerException
System.out.println("The " + i + " coordinate of the array: "
+ lang.get(i));
}
}
But I get a NullpointerException when I try to iterate over the array.