Java - NullPointerException when parsing JSON despite getOrDefault

3584 views java

I'm trying to parse JSON and decided to use getOrDefault to deal with null values. According to the doc: Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

However when it's parsing the following line from JSON - "theDate": null I'm getting a NullPointerException . While debugging I noticed that String dateFromJson is null despite the getOrDefault call. But I expected it to have a default String value.

What could be wrong with my implementation and understanding here?

public static Long parseDate(JSONObject jsonObj, String date, String default) throws
            java.text.ParseException {
        String dateFromJson = (String) jsonObj.getOrDefault(date, default);
        if (Objects.equals(dateFromJson, default)) {
                return System.currentTimeMillis();        
    return DATE_FORMAT.parse(dateFromJson).getTime();

answered question

and what is the value of default?

How can you be sure String default is not null? It seems to be the case if json contains null value for "theDate"

1 Answer


Isn't default a keyword in Java? And so shouldn't be used as a variable name?

posted this

Have an answer?


Please login first before posting an answer.