Reading from geojson starting from specific word

75 Views Asked by At

I know this question is already mentioned here:

Start reading the file after a specific word

However, in my case, I want to read a .geojson file from a specific word (including that word) and save that in a String.

{"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]
        ]
      }
    }
  ]
}

My String should start with {"type": "Linestring" followed by the rest of the file. It has to be applicable for any Linestring geojson.

My code so far:

BufferedReader br = new BufferedReader(new FileReader(
                "C:\\Users\\****\\Desktop\\test2.geojson"));
        String line;
        while ((line = br.readLine()) != null) {
            if (line.contains("LineString")) {

                break; // breaks the while loop
            }
        }
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

        br.close();

Can anyone push me in the right direction?

Cheers!

1

There are 1 best solutions below

0
On BEST ANSWER

Code below worked for me!

To get to the desired piece of JSON, I first had to walk through the tree hierarchy. This means opening "features", "geometry" and finally "coordinates" to get to the coordinates. Add the Linestring and brackets in the end to transform to a proper JSON file again.

    // look for features
    if (jsoninput.contains("features")) {
        jsonArray1 = obj.getJSONArray("features");
        System.out.println(jsonArray1+ "\n");
    }

    // look for geometry
    if (jsoninput.contains("geometry")) {
        jsonArray2 = obj.getJSONObject("geometry");
        System.out.println(jsonArray2+ "\n");
        jsonArray3 = jsonArray2.getJSONArray("coordinates");
        output = ""+jsonArray3;
        System.out.println(output);
    }


    // no features of geometry, just check "coordinates"
    if (!jsoninput.contains("features") & !jsoninput.contains("geometry")) {
        jsonArray4 = obj.getJSONArray("coordinates");
        output = ""+jsonArray4;
        System.out.println(output);
    }

    // output is just a String of coordinates, add LineString prefix and  
    // brackets to make it a proper JSON again                     
    String finaloutput = "{\"type\": \"LineString\",\"coordinates\":"
            + output + "}";

    System.out.println(finaloutput);