1

I'm trying to parse a json file using the org.json.simple library and I'm getting null pointer exception when I try to instantiate the iterator with the Map.

@SuppressWarnings("unchecked")
public static void main(String[] args) {

    JSONParser parser = new JSONParser();

    try {

        Object obj = parser.parse(new FileReader("wadingpools.json"));

        JSONObject jsonObject = (JSONObject) obj;
        System.out.println(jsonObject);

        JSONArray featuresArray = (JSONArray) jsonObject.get("features");
        Iterator iter = featuresArray.iterator();

        while (iter.hasNext()) {
            Map<String, String> propertiesMap = ((Map<String, String>) jsonObject.get("properties"));
            Iterator<Map.Entry<String, String>> itrMap = propertiesMap.entrySet().iterator();
            while(itrMap.hasNext()){
                Map.Entry<String, String> pair = itrMap.next();
                System.out.println(pair.getKey() + " : " + pair.getValue());
            }
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }

}

}

Here is a snippet of part of the JSON file. I'm trying to get the NAME in the properties object.

{
    "type": "FeatureCollection",
    "crs": {
        "type": "name",
        "properties": {
            "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
        }
    },
    "features": [{
            "type": "Feature",
            "properties": {
                "PARK_ID": 393,
                "FACILITYID": 26249,
                "NAME": "Wading Pool - Crestview",
                "NAME_FR": "Pataugeoire - Crestview",
                "ADDRESS": "58 Fieldrow St."
            },
Pshemo
  • 113,402
  • 22
  • 170
  • 242
Dispatcher
  • 53
  • 8

1 Answers1

2

At (Map<String, String>) jsonObject.get("properties") you are trying to access properties from your "root" object (held by jsonObject) which doesn't have such key. You probably wanted to get value of that key from object held by features array. You already created iterator for that array, but you never used it to get elements held by it. You need something like

while (iter.hasNext()) {
    JSONObject tmpObject = (JSONObject) iter.next();
    ...
}

and call get("properties") on that tmpObject.

Pshemo
  • 113,402
  • 22
  • 170
  • 242
  • 1
    @VincentArrage You are welcome. BTW you should take a look at [How to efficiently iterate over each entry in a 'Map'?](https://stackoverflow.com/q/46898). Explicitly using iterator is nice if you want to modify map (like remove some entries). If you just want to print its elements code using for-each may be easier to write and maintain. – Pshemo Feb 06 '18 at 18:01