Skip to content

Conversation

@OwenSanzas
Copy link
Contributor

Add type checking before casting parse() results to JSONArray/JSONObject. When parse() returns an unexpected type (e.g., String for malformed input), the code now throws a descriptive JSONException instead of ClassCastException.

This prevents unchecked exceptions from propagating to callers who only expect JSONException from these methods.

Fixes #1034

Add type checking before casting parse() results to JSONArray/JSONObject.
When parse() returns an unexpected type (e.g., String for malformed input),
the code now throws a descriptive JSONException instead of ClassCastException.

This prevents unchecked exceptions from propagating to callers who only
expect JSONException from these methods.

Fixes stleary#1034
@stleary
Copy link
Owner

stleary commented Jan 27, 2026

Changes look OK, but where are the unit tests to confirm the new behavior?

[stleary 1/28/2026] Issue fixed

@stleary
Copy link
Owner

stleary commented Jan 27, 2026

What problem does this code solve?
Replace ClassCastException with a more useful JSONException in JSONML toJSONArray() and toJSONObject()

Does the code still compile with Java6?
Yes

Risks
Low

Changes to the API?
Yes, a different exception is thrown. API changes are not allowed, but in this case the ClassCastException is arguably a flaw in the original design.

Will this require a new release?
No

Should the documentation be updated?
No

Does it break the unit tests?
No, and new unit tests were added but no new unit tests were added. This will need to be corrected in order to complete this PR.

Was any code refactored in this commit?
No

Review status
APPROVED

Starting 3-day comment window

Added comprehensive test coverage for safe type casting:

Exception cases (should throw JSONException, not ClassCastException):
- Malformed XML causing type mismatch in toJSONArray()
- Type mismatch in toJSONObject()

Valid cases (should continue to work):
- Valid XML to JSONArray conversion
- Valid XML to JSONObject conversion

These tests verify the fix for issue stleary#1034 where ClassCastException
was thrown when parse() returned unexpected types.
@sonarqubecloud
Copy link

@OwenSanzas
Copy link
Contributor Author

Hey @stleary, all requested changes are complete. Could you please take a look?

After the fix:

  1. PoC for ClassCastException in JSONML.toJSONArray due to Unsafe Type Cast #1034 is mitigated
  2. All newly-added unit tests pass
  3. All existing unit tests pass

@stleary stleary merged commit d092d09 into stleary:master Jan 30, 2026
9 checks passed
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

Successfully merging this pull request may close these issues.

ClassCastException in JSONML.toJSONArray due to Unsafe Type Cast

2 participants