Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
PurnAnrup opened this issue Oct 31, 2024 · 1 comment
Open

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

PurnAnrup opened this issue Oct 31, 2024 · 1 comment

Comments

@PurnAnrup
Copy link

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

  • Library Version: [1.1] for the response "null"
  • Library Version: [1.5.4] for the response null
  • Environment: [Provide any relevant details about your environment, e.g., Java version, IDE, etc.]
@PurnAnrup
Copy link
Author

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

  • When the key is not present in the JSON, o is null, and we want to return the defaultValue.
  • When the key is present but the value is explicitly set to null, o will be an instance of Null, and isExplicitNull() will return true, prompting the method to return the defaultValue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant