jettison-json / jettison

Apache License 2.0
46 stars 28 forks source link

`optString` Method Does Not Return Default Value for Explicit Null #105

Open PurnAnrup opened 3 hours ago

PurnAnrup commented 3 hours ago

Sure! Here’s the issue description formatted in Markdown:

## Description

The `optString` method in the Jettison library is expected to return the provided default value when the key is either absent or explicitly set to `null`. However, it currently returns `"null"` (as a string) for keys that are explicitly set to `null`, instead of the specified default value.

### Steps to Reproduce

1. Create a JSON object with a key explicitly set to `null`.
   ```json
   {
       "name": null
   }
  1. Call the optString method with the key and a default value.
    JSONObject jsonObject = new JSONObject("{\"name\": null}");
    String result = jsonObject.optString("name", "Default Name");

Expected Behavior

The expected output should be:

"Default Name"

Actual Behavior

The actual output is:

"null" (as a string)

Additional Information

PurnAnrup commented 3 hours ago

Suggested Fix for optString Method

To address the issue where optString does not return the expected default value when the key is absent or explicitly set to null, I propose the following modification:

public String optString(String key, String defaultValue) {
    Object o = opt(key);
    return (o == null ||  ((Null) o).isExplicitNull()) ? defaultValue : o.toString();
}

Reasoning