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."
            },

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@VincentArrage You are welcome. BTW you should take a look at How to efficiently iterate over each entry in a 'Map'?. 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.

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.