Search code examples
javajsonnode

How to extract an array from a JsonNode?


I have the following input:

enter image description here

I want to extract lat and long. I tried the following implementation, but I received null pointer exception for positionNode.get(i + 1).asDouble()

private List<CoordinateBE> getCoordinate(final JsonNode positionNode) {
        
        final List<CoordinateBE> listOfEntrances = new ArrayList<>();
        for (int i = 0; i < positionNode.size(); i = i + 2) {
            final CoordinateBE coordinateBE = new CoordinateBE();
            coordinateBE.setLatitude(positionNode.get(i).asDouble());
            coordinateBE.setLongitude(positionNode.get(i + 1).asDouble());  <--- Null Pointer Exception !!
            listOfEntrances.add(coordinateBE);
        }
        return listOfEntrances;
    }

How can I fix the above implementation ?


Solution

  • Your input "[{"lat":35.65, "lng":139.61}]" is an array of one element. The loop you're using goes through every other element, because of i = i + 2

    The code inside your setLatitude gets the element at position 0 in your array, which is {"lat":35.65, "lng":139.61}, and converts it into a Double.

    The code inside your setLongitude tries to retrieve the element at position 1, which is null. The method asDouble on a null object causes the NullPointerException.

    Here's how you can fix it:

        private List<CoordinateBE> getCoordinate(final JsonNode positionNodes) {
            
            final List<CoordinateBE> listOfEntrances = new ArrayList<>();
            for (JsonNode positionNode : positionNodes) {
                final CoordinateBE coordinateBE = new CoordinateBE();
                coordinateBE.setLatitude(positionNode.get("lat").asDouble());
                coordinateBE.setLongitude(positionNode.get("lng").asDouble());
                listOfEntrances.add(coordinateBE);
            }
            return listOfEntrances;
        }
    

    Notice that the for loop iterates through every object in positionNodes, and lat and lng are extracted using their name rather than position.