Compare commits

...
230 Commits
Author SHA1 Message Date
indroneel 67448d00f0 minor cleanup and changes to the build process 2026-11-10 23:06:47 +05:30
Sean Leary 2cd0a8c211 Merge pull request #1093 from Lyin-OTTF/fix/xml-serialize-escape-whitespace
Fix TAB/LF/CR escape when serializing to XML
2026-10-31 08:34:32 -05:00
Sean Leary bc90ee497b Merge pull request #1095 from Lyin-OTTF/fix/gh-1076-fromjson-binding-javadoc
Update Javadocs for fromJson()
2026-10-31 08:33:12 -05:00
Lyin-OTTF 88b6be9f84 Clarify fromJson(Class) Javadoc: type registry does not exist
The fromJson(Class) Javadoc claimed that only classes "explicitly supported
and registered within the JSONObject context" can be deserialized, and
declared an IllegalArgumentException for classes outside that set. No such
registry exists: fromJson instantiates any class with a no-arg constructor and
writes every non-static declared field whose name matches a JSON key, widening
access with setAccessible(true). Private and transient fields are populated,
and JSONPropertyIgnore does not apply because it only suppresses the bean to
JSONObject direction.

The binding rules are already released, so changing them here would break
existing users. Instead document what actually happens, point out that binding
is driven by whatever keys the JSON contains, and replace the non-existent
IllegalArgumentException with the JSONException the method really throws.

Adds JSONObjectTest#jsonObjectParseFromJson_10 to pin the current binding
behavior so the documentation cannot drift from the implementation again. The
test bean is named FromJsonKeyBindingExample and its fields spell out how they
are declared (privateString, privateBoolean, transientString,
ignoredGetterBoolean), so the test reads as a binding example rather than as a
scenario.

Fixes #1076
2026-10-26 08:38:38 +08:00
Lyin-OTTF fea3a2ce32 Escape TAB/LF/CR again when serializing to XML
XML.mustEscape() is shared by XML.escape() (serialization) and
XMLTokener.unescapeEntity() (parsing), but the two callers need opposite
answers for #x9/#xA/#xD. #1070 added those codepoints to the valid-range
clause to fix unescape("
"), which also stopped XML.toString() and
JSONML.toString() from escaping literal TAB, LF and CR. Literal
occurrences of these characters are subject to whitespace normalization
by conforming XML parsers, so a value like "Lettuce\nTomato" loses its
line breaks when the generated XML is read back by any standard parser.
This regressed #1092.

Split the two concerns: mustEscape() returns true for every ISO control
character again (serialization), and the new isValidXmlCharacter() keeps
the previous numeric-reference validation for the parsing path, so 	,

 and 
 are still accepted (#1059/#1070 behaviour unchanged).

isValidXmlCharacter() stays as strict as before for the C1 control
characters (#x7F-#x9F): they fall inside [#x20-#xD7FF] and are legal XML
1.0 characters, but this library has always rejected references to them,
and widening the range here would silently change what XML.toJSONObject
accepts. Only the serialization of TAB/LF/CR changes.

Fixes #1092
2026-10-26 08:35:09 +08:00
Sean Leary 9926542da1 Merge pull request #1094 from labkey-jeckels/fb_share_parsed_keys_1091
Share repeated object keys within a parse (#1091)
2026-10-25 11:46:26 -05:00
labkey-jeckels 293bbf65d3 Share repeated object keys within a parse (#1091) 2026-10-20 09:54:00 -07:00
Sean Leary 69383f746d Merge pull request #1090 from JimmyLiuJia/fix/json-pointer-fragment-plus
Preserve plus signs in JSONPointer URI fragments
2026-10-15 07:50:28 -05:00
Sean Leary e5e97f87b1 Specify requirements for code changes and pull requests
Added requirements for code changes and pull requests to ensure backward compatibility and proper issue reporting.
2026-10-11 11:36:41 -05:00
JimmyLiuJia 4713079d13 Merge master and resolve JSONPointerTest conflict 2026-10-11 23:41:08 +08:00
Sean Leary 406abf8b76 Merge pull request #1088 from fahadaldajani92/test/jsonpointer-issue-1081
test: cover literal tilde tokens in JSONPointer
2026-10-11 08:39:01 -05:00
Sean Leary 5e9b4f4e27 Merge pull request #1087 from PHJ2000/fix-properties-defaults-only
Fix Property enumeration without local entries
2026-10-11 08:33:39 -05:00
JimmyLiuJia 564acf4eb1 Preserve plus signs in JSONPointer URI fragments 2026-10-11 16:21:40 +08:00
Sean Leary 6527427aad Merge pull request #1085 from Boulea7/fix/jsonml-keep-strings-entities
Fix JSONML text double decoding with keepStrings
2026-10-08 10:16:18 -05:00
Fahad Al-Dajani 23bc68f227 test: cover literal tilde tokens in JSONPointer 2026-10-08 16:55:26 +03:00
Sean Leary babc520380 Merge pull request #1084 from zemiles/master
Fix reserved childNodes attribute check in JSONML
2026-10-05 20:14:31 -05:00
PHJ2000 3d2f7e07ec Preserve inherited properties without local entries 2026-10-05 18:17:59 +09:00
boulea7 f3c83d8349 Fix JSONML text double decoding with keepStrings 2026-10-02 18:18:04 +08:00
안승현 d38bff8957 Extract childNodes constant in JSONML
Replace the four repeated "childNodes" literals with a private
static final constant.

Address SonarQube rule java:S1192 without changing parsing behavior.
2026-10-01 17:15:16 +09:00
안승현 5dfa60ba0a Fix reserved childNodes attribute check in JSONML
JSONML object-form parsing uses "childNodes" to store child elements,
but the reserved-attribute check incorrectly used "childNode".

This rejected ordinary "childNode" attributes while accepting
"childNodes" attributes, whose values could then be overwritten
by the element's children.

Correct the reserved-attribute check to use "childNodes" and add
JUnit 4 regression tests covering:
- Rejection of reserved "childNodes" attributes in object-form parsing
- Preservation of ordinary "childNode" attributes and child content
- Continued rejection of reserved "tagName" attributes
- Preservation of both attribute names in array-form parsing

Verify each scenario with keepStrings enabled and disabled.

Validation:
- All 40 JSONML tests pass
- Full test suite: 807 passed, 6 skipped on Java 11 with Gradle 8.13
- Both bug regression tests fail against the original implementation

Fixes #1080
2026-10-01 16:55:38 +09:00
Sean Leary 18e8ef6e61 Merge pull request #1083 from DarkLight606/fix/1082
Fix a parsing error in JSONPointer.toURIFragment()
2026-09-30 08:09:17 -05:00
Denys Khalitov f875ab2fc7 Escape ~ and / in JSONPointer.toURIFragment()
toURIFragment() URL-encoded each reference token but skipped the ~0/~1
escaping from RFC 6901. Tokens are stored as literal key names, so a key
containing / or ~ produced a fragment that parsed back to a different
pointer. Apply escape() before encoding, as toString() already does.

Fixes #1082
2026-09-26 17:19:47 +03:00
Sean Leary b55c69e650 Merge pull request #1078 from jakezwang/fix/json-pointer-double-unescape
Decode JSONPointer tokens once only
2026-09-23 12:09:16 -05:00
Sean Leary 4f822e0292 Merge pull request #1077 from Mahmoodifar/fix/parser-configuration-precedence
Apply explicit parser configuration to nested values
2026-09-20 21:44:30 -05:00
Jake Wang 775c98ea41 Avoid decoding JSON Pointer tokens twice 2026-09-18 20:10:16 -04:00
sajad mahmoodifar 9f3b527d9f fix: restore tokener configuration after parsing 2026-09-18 16:53:59 +03:30
sajad mahmoodifar 0ae8d5ab4f fix: apply explicit parser configuration
Fixes #945
2026-09-18 13:25:36 +03:30
Sean Leary 8746735758 Merge pull request #1074 from XIAYM-gh/master
Fix strict mode failure when JSONTokener.next() and back() are called before parsing
2026-09-13 07:57:15 -05:00
XIAYM-gh a25f83a0e4 Strip JSONTokener#isAtStart() 2026-09-11 03:57:03 +08:00
XIAYM-gh 359b43d8df Apply corner-case fixes under instruction 2026-09-04 08:09:14 +08:00
XIAYM-gh bcbbc89568 Fixes corner case where strict mode isn't working when JSONTokener's next() and back() are called first 2026-09-02 20:31:40 +08:00
Sean Leary 4f859fdf3b Merge pull request #1072 from mechko/1071-xml-tostring-name-validation
#1071: reject invalid XML element names in XML.toString (CWE-91)
2026-08-24 12:22:44 -05:00
Mirko SwillusandClaude 3dd0ec02f2 #1071: narrow tag-name check to XML metachars only
Per review on #1072: reject only < > & " ' / in element names to
close the CWE-91 injection vector, and drop the full XML 1.0 Name
validation to preserve backwards compatibility for callers that
emit non-well-formed but non-injecting tag names.

Co-Authored-By: Claude <[email protected]>
Claude-Session: https://claude.ai/code/session_01MTGnYg5v1QxaqqfDKHKTVr
2026-08-20 17:14:07 +02:00
Sean Leary 6c14048079 Merge pull request #1073 from stleary/pre-release-20260814
20260814 prep for next release
2026-08-14 11:09:30 -05:00
Sean Leary 34efda6423 pre-release-20260814 initial commit 2026-08-14 10:54:22 -05:00
Sean Leary 22ab2fb724 Update jar file link in README 2026-07-31 15:28:31 -05:00
Sean Leary 392a352901 Fix formatting of the latest release jar file link 2026-07-31 15:26:28 -05:00
Sean Leary b594a3229c Merge pull request #1070 from dong0713/fix/xml-unescape-whitespace-control-chars
Fix XML.unescape rejecting valid whitespace numeric character references
2026-07-29 07:50:07 -05:00
Mirko SwillusandClaude 6b993e2e47 #1071: extract inRange helper to satisfy Sonar S3776
isXmlNameStart's alternating &&/|| chain scored cognitive complexity 28.
Extracting inRange(cp, lo, hi) collapses it to a flat || sequence and
keeps the range list 1:1 with the XML 1.0 NameStartChar production.
isXmlNameChar updated the same way. No behaviour change.

Co-Authored-By: Claude <[email protected]>
2026-07-24 10:57:24 +02:00
Mirko SwillusandClaude e2cfb5a641 #1071: reject invalid XML element names in XML.toString (CWE-91)
XML.toString emitted JSONObject keys verbatim as tag names, so a key
containing '<', '>' or '/' broke out of its element and injected
arbitrary sibling structure into the output. Per #294/#123 the agreed
approach is to throw on invalid input rather than mangle it.

- Add mustBeXmlName / isXmlNameStart / isXmlNameChar implementing the
  XML 1.0 (5th ed.) Name production, code-point aware.
- Validate tagName at method entry and each key at the top of the key
  loop (skipping the cDataTagName sentinel).
- Rewrite XMLTest.shouldHandleIllegalJSONNodeNames and
  XMLConfigurationTest.shouldHandleIllegalJSONNodeNames (previously
  documenting the pass-through behaviour) to assert the throw.
- Add XMLTest.toStringRejectsElementInjectionInKey covering the #1071
  payload and an invalid caller-supplied tagName.
- Add XMLTest.toStringAcceptsValidXmlNames covering hyphen/dot/
  underscore/colon, Latin-1 letters, and the cDataTagName sentinel.

Fixes #1071. Also resolves the long-standing well-formedness question
in #166 / #294 / #308.

Co-Authored-By: Claude <[email protected]>
2026-07-23 14:36:42 +02:00
dong0713 94854a1dfa Fix XML.unescape rejecting valid whitespace numeric character references
XML.mustEscape() is shared by both XML.escape() (serialization) and
XMLTokener.unescapeEntity() (deserialization). While the method's Javadoc
and comment quote the W3C XML 1.0 valid-character range
(#x9 | #xA | #xD | [#x20-#xD7FF] | ...), the implementation only checked
[#x20-#xD7FF] in its range clause, omitting #x9/#xA/#xD.

Although the ISO-control clause excluded those three codepoints, the
negated range clause still marked them as 'must escape', so unescapeEntity()
threw JSONException for the XML-allowed control characters TAB, LF and CR.

This broke XML.unescape("&#10;") and XML.toJSONObject("<a>&#10;</a>"),
both of which worked in v20251224 and regressed after #1045 (v20260522).

Align the range clause with the W3C spec by explicitly allowing #x9, #xA
and #xD, matching the comment that was already documented.

Fixes #1059
2026-07-20 17:42:02 +08:00
Sean Leary 1795e8cf26 Merge pull request #1069 from stleary/pre-release-20260719
20260719 prep for next release
2026-07-19 14:04:18 -05:00
Sean Leary da757c6656 pre-release-20260719 oops forgot to update new unit tests for strict mode 2026-07-19 13:48:18 -05:00
Sean Leary d24bc9e5d6 pre-release-20260719 initial commit 2026-07-19 12:51:08 -05:00
Sean Leary 80efb529d7 Merge pull request #1068 from stleary/max-number-length-config
Max number length config for BigInteger and BigDecimal
2026-07-19 12:43:09 -05:00
Sean Leary 9953b76050 max-number-length-config sonarqube fixes 2026-07-16 13:23:39 -05:00
Sean Leary a28328c706 Merge pull request #1067 from mechko/1063-biginteger-exponent-dos
#1063: bound BigDecimal→BigInteger expansion in objectToBigInteger (completes CVE-2026-59171 fix)
2026-07-16 12:31:17 -05:00
Mirko SwillusandClaude 703ac34a55 #1063: add JSONParserConfiguration overloads for getBigInteger/optBigInteger
Per review on #1067:
- objectToBigInteger(val, dflt, JSONParserConfiguration) uses
  cfg.getMaxNumberLength() for the digit-count guard; -1 disables it.
  Existing 2-arg form delegates with a default config.
- New public overloads on JSONObject and JSONArray:
  getBigInteger(key, cfg) / optBigInteger(key, dflt, cfg).
  Existing methods delegate with a default config.
- objectToBigDecimal left unchanged (no expansion path; agreed on PR).
- Tests cover default (1000), raised (2000), lowered (5), disabled (-1),
  null config, and JSONArray overloads.

Co-Authored-By: Claude <[email protected]>
2026-07-16 11:42:40 +02:00
Mirko SwillusandClaude e40d933d50 #1063: add comment to expected-exception catch block (SonarCloud java:S108)
Co-Authored-By: Claude <[email protected]>
2026-07-14 13:36:46 +02:00
Mirko SwillusandClaude fce83c91bb #1063: bound BigDecimal->BigInteger expansion in objectToBigInteger
Completes the CVE-2026-59171 fix started in ab92bb9 / #1065. The
1000-char length guard in stringToValue admits short exponent-notation
literals (e.g. 1e100000000, 11 chars) which are stored compactly as
BigDecimal and only expand when getBigInteger/optBigInteger calls
BigDecimal.toBigInteger(), materialising ~10^8 digits and stalling the
thread or throwing OOM.

Guard both toBigInteger() sites in objectToBigInteger by rejecting any
BigDecimal whose integer part would exceed
ParserConfiguration.DEFAULT_MAX_NUMBER_LENGTH decimal digits
(precision() - scale(), both O(1) reads). Returns defaultValue on
overflow, matching the method's existing behaviour for non-finite and
unparseable values.

Covers JSONObject.getBigInteger/optBigInteger and
JSONArray.getBigInteger/optBigInteger (all delegate to this helper).

Adds JSONObjectTest.getBigIntegerHugeExponentReturnsDefault with a 5s
timeout so a regression fails fast rather than hanging CI.

Co-Authored-By: Claude <[email protected]>
2026-07-14 11:59:27 +02:00
Sean Leary 90563eb877 1063-option-3 parserConfig set max len 2026-07-13 15:33:12 -05:00
Sean Leary 1efb5f6c43 Merge pull request #1065 from Damien-Warren-206/master
Fixes CVE-2026-59171
2026-07-06 12:23:25 -05:00
Damien Warren ab92bb9088 Fixes CVE-2026-59171 2026-07-03 09:21:58 -07:00
Sean Leary c91d821dbe Merge pull request #1062 from Fahmida-Hossain-Charu/pr/refactor-cdl-row-serialization
Refactor CDL row serialization for readability
2026-06-21 07:09:27 -05:00
Sean Leary 4a23fd8d9b Merge pull request #1061 from stleary/restore-lenient-jsonarray
restore-lenient-jsonarray allow consecutive commas and insert null
2026-06-18 11:02:35 -05:00
Fahmida-Hossain-Charu 8353b59fa0 Address CDL row serialization review comments 2026-06-17 17:59:07 +06:00
Fahmida-Hossain-Charu 26ee6eb25a Refactor CDL row serialization 2026-06-17 04:17:48 +06:00
Sean Leary ad26e94274 restore-lenient-jsonarray fix some sonarcube issues 2026-06-15 20:56:17 -05:00
Sean Leary c073157a61 restore-lenient-jsonarray initial commit 2026-06-15 16:43:46 -05:00
Sean Leary 33a4698428 Merge pull request #1058 from stleary/docs-and-warnings-cleanup
docs-and-warnings-cleanup
2026-06-01 09:34:43 -05:00
Sean Leary d84fa1af88 docs-and-warnings-cleanup cleanup some doc files, update pom for deployment, fix some JSONObject warnings 2026-05-29 10:38:42 -05:00
Sean Leary 968a592260 Merge pull request #1054 from stleary/pre-release-20260522
pre-release-20260522 prep for next release
2026-05-22 12:57:40 -05:00
Sean Leary 3665aad82b pre-release-20260522 doc and build updates for release 2026-05-22 12:54:09 -05:00
Sean Leary d749ee16ab Merge pull request #1053 from stleary/update-security-md-with-key
update security.md with key data
2026-05-15 21:35:37 -05:00
Sean Leary 649598338f update-security-md-with-key new security.md file, also fixed 1000 level jsonarray test that fails on my laptop 2026-05-11 11:54:52 -05:00
Sean Leary 896ce0fb74 Merge pull request #1046 from yuki-matsuhashi/master
Validate XML numeric character references before string construction
2026-03-26 11:52:49 -05:00
Yuki Matsuhashi 1877069780 Validate XML numeric character references before string construction 2026-03-24 04:22:50 +09:00
Sean Leary b959027aa2 Merge pull request #1044 from yuki-matsuhashi/1043-ignore-static
Ignore static fields in JSONObject.fromJson()
2026-03-16 09:24:24 -05:00
Yuki Matsuhashi 039f331d7d Add comment for empty test constructor 2026-03-13 01:54:58 +09:00
Yuki Matsuhashi 94e340002b Ignore static fields in JSONObject.fromJson() 2026-03-13 01:23:59 +09:00
Sean Leary 6230128f59 Merge pull request #1041 from stleary/license-clarification
Enhance README with license clarification
2026-02-22 15:14:00 -06:00
Sean Leary ff264ef647 Enhance README with license clarification
Added license clarification
2026-02-18 14:50:17 -06:00
Sean Leary a37aa69480 Merge pull request #1039 from pratiktiwari13/bugfix/empty-force-list
Fixes the issue of losing the array if an empty forceList element or a tag is in the middle or the end
2026-02-03 11:15:58 -06:00
Pratik Tiwari 510a03ac36 Fixes #1040, Aligns non-forceList behaviour with forceList 2026-01-31 10:34:24 +05:30
Sean Leary 538afc3d78 Merge pull request #1038 from OwenSanzas/fix-xmltokener-unescapeentity
Fix input validation in XMLTokener.unescapeEntity()
2026-01-30 08:13:34 -06:00
Sean Leary d092d0903c Merge pull request #1037 from OwenSanzas/fix-jsonml-classcast
Fix ClassCastException in JSONML.toJSONArray and toJSONObject
2026-01-30 08:12:16 -06:00
Pratik Tiwari 7a8da886e7 Remove unnecessary conditions 2026-01-30 19:29:46 +05:30
OwenSanzas 0737e04f8a Add unit tests for JSONML ClassCastException fix
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 #1034 where ClassCastException
was thrown when parse() returned unexpected types.
2026-01-28 10:07:34 +00:00
OwenSanzas 592e7828d9 Add unit tests for XMLTokener.unescapeEntity() input validation
Added comprehensive test coverage for numeric character reference parsing:

Exception cases (should throw JSONException):
- Empty numeric entity: &#;
- Invalid decimal entity: &#txx;
- Empty hex entity: &#x;
- Invalid hex characters: &#xGGG;

Valid cases (should parse correctly):
- Decimal entity: &#65; -> 'A'
- Lowercase hex entity: &#x41; -> 'A'
- Uppercase hex entity: &#X41; -> 'A'

These tests verify the fixes for issues #1035 and #1036.
2026-01-28 09:58:35 +00:00
OwenSanzas 6c1bfbc7a5 Refactor XMLTokener.unescapeEntity() to reduce complexity
Extracted hex and decimal parsing logic into separate methods to
address SonarQube complexity warning:
- parseHexEntity(): handles &#xABC; format
- parseDecimalEntity(): handles &#123; format

This reduces cyclomatic complexity while maintaining identical
functionality and all validation checks.
2026-01-28 09:52:25 +00:00
OwenSanzas 534ce3c4d1 Fix input validation in XMLTokener.unescapeEntity()
Fix StringIndexOutOfBoundsException and NumberFormatException in
XMLTokener.unescapeEntity() when parsing malformed XML numeric
character references.

Issues:
- &#; (empty numeric reference) caused StringIndexOutOfBoundsException
- &#txx; (invalid decimal) caused NumberFormatException
- &#xGGG; (invalid hex) caused NumberFormatException

Changes:
- Add length validation before accessing character positions
- Add isValidHex() and isValidDecimal() helper methods
- Throw proper JSONException with descriptive messages

Fixes #1035, Fixes #1036
2026-01-27 11:40:18 +00:00
OwenSanzas 9d14246bee Fix ClassCastException in JSONML.toJSONArray and toJSONObject
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
2026-01-27 11:36:46 +00:00
Pratik Tiwari 995fb840f7 Fixes the issue of losing the array if an empty forceList element or a tag is in the middle or the end 2026-01-02 21:20:53 +05:30
Sean Leary e635f40238 Merge pull request #1027 from Simulant87/1023-set-default-locale
Save/restore default locale in test
2025-12-29 19:42:57 -06:00
Sean Leary d5e744ca90 Merge pull request #1028 from Simulant87/fix-sonarqube-reliability-issues
Refactoring: Fix sonarqube reliability issues
2025-12-29 19:42:02 -06:00
Sean Leary e0c4086168 Merge pull request #1029 from Simulant87/external-javadoc-badge
add badge to external hosted javadoc
2025-12-29 19:41:31 -06:00
Sean Leary cf653682be Merge pull request #1030 from stleary/pre-release-20251224
pre-release-20251224 Prep for next release
2025-12-24 09:16:47 -06:00
Sean Leary 24bba97c1d pre-release-20251224 update docs and builds for next release 2025-12-24 09:05:18 -06:00
Simulant 96353de304 add badge to external hosted javadoc 2025-12-21 23:16:01 +01:00
Simulant 8cbb4d5bb3 Fix sonarqube reliability issues 2025-12-20 22:57:24 +01:00
Simulant 421abfdc1f save and restore the current default locale, to avoid any side effects on other executions in the same JVM 2025-12-20 22:27:45 +01:00
Sean Leary 128fb42ccc Merge pull request #1021 from Simulant87/update-build-script
Update github build actions, add LTS JDK 25 build
2025-11-18 07:26:35 -06:00
Simulant87 f8e6dfdc63 Merge pull request #3 from Simulant87/update-readme
Update README.md tested on java 25
2025-11-14 15:49:30 +01:00
Simulant87 3bc98dfc7f Update README.md tested on java 25 2025-11-14 15:49:09 +01:00
Simulant87 005dc7b49e add build for LTS JDK 25 2025-11-14 15:47:58 +01:00
Simulant87 d38cb064fd reset setup-java to version 1 for 1.6 build 2025-11-14 15:45:41 +01:00
Simulant87 e9a7d7c72e add distribution to java 1.6 build 2025-11-14 15:40:21 +01:00
Simulant87 73c582e129 update github actions to version 5
consistently update all actions checkout, setup-java, upload-artifactory to version 5
2025-11-14 15:29:52 +01:00
Sean Leary a6ca84074a Merge pull request #1020 from Abhineshhh/fix/support-java-records
Fix: Support Java record accessors in JSONObject
2025-11-11 20:19:42 -06:00
Sean Leary 8c14e96c44 Merge pull request #1017 from Md-Yasir/enhancement/refactors
Code Refactors
2025-11-09 19:02:49 -06:00
AbhineshJha 8f3b0f1c13 Add runtime record detection for backward compatibility 2025-11-02 22:32:44 +05:30
AbhineshJha f2acf8af69 Optimize method name exclusion using Set lookup instead of multiple equals checks 2025-11-01 19:33:29 +05:30
AbhineshJha fd1eee9c3b Add comprehensive edge case tests for record support 2025-11-01 19:33:29 +05:30
AbhineshJha 2550c692cf Refactor: Extract isRecordStyleAccessor helper method 2025-11-01 19:33:29 +05:30
AbhineshJha 20f5200000 Fix: Support Java record accessors in JSONObject 2025-11-01 19:33:29 +05:30
Sean Leary 25f355a953 Merge pull request #1006 from sk02241994/feature-1003
1003: Implement JSONObject.fromJson() with unit tests
2025-10-31 11:25:03 -05:00
sk02241994 42800c208a Updating to work with java 1.6 2025-10-28 13:06:11 +11:00
md-yasir 0cdc5e5170 Reverted Constructor access to public 2025-10-25 20:51:50 +05:30
md-yasir ac65ee0490 Revert "Refactored stop conditions to be invariant by using while loop."
This issue can be ignored
2025-10-25 20:37:54 +05:30
md-yasir 39e8ead7cd Added java doc for deprecated decoration 2025-10-24 09:37:46 +05:30
md-yasir 6dd878d3c9 Deprecated public constructors instead of making it private. 2025-10-24 09:10:53 +05:30
md-yasir 2c6082a0a2 Refactored stop conditions to be invariant by using while loop. 2025-10-23 22:50:12 +05:30
md-yasir 5dc1031d17 Made JSONMl constructor to private and refactored ternary operations to independent statement in L243 2025-10-23 22:38:01 +05:30
md-yasir 1de42aa4fd Made CookieList constructor to private. 2025-10-23 22:37:00 +05:30
md-yasir c13b57ca26 Made Cookie constructor to private. 2025-10-23 22:36:53 +05:30
sk02241994 f92f281620 Updating to work with java 1.6 2025-10-23 17:33:37 +11:00
sk02241994 8ccf5d7525 Removing the interface classes and simplifying the implementation to use if else instead 2025-10-23 17:32:07 +11:00
sk02241994 a7c193090a Updating docs 2025-10-16 14:23:30 +11:00
sk02241994 c4c2beb874 Limiting implemetation by removing the new classes. 2025-10-16 14:19:19 +11:00
sk02241994 9adea9e12d Updating to work with java 1.6 2025-10-13 12:39:15 +11:00
sk02241994 7465da858c - Updating for java 1.6
- Resolving Sonar cube issues.
2025-10-13 12:39:15 +11:00
sk02241994 0521928463 - Added implementation for Enum and Map
- Moving the CustomClass to data folder.
- Removing JSONBuilder.java
- Moving the implementation of JSONBuilder to JSONObject.
2025-10-13 12:39:14 +11:00
sk02241994 fbb6b3158e Updating to work with java 1.6 2025-10-13 12:39:14 +11:00
sk02241994 ebc13d6685 Updating to work with java 1.6 2025-10-13 12:39:13 +11:00
sk02241994 7d28955216 Updating to work with java 1.6 2025-10-13 12:39:13 +11:00
sk02241994 83a0e34be5 1003: Implement JSONObject.fromJson() with unit tests 2025-10-13 12:39:12 +11:00
Sean Leary 3e8d1d119f Merge pull request #1014 from Md-Yasir/enhancement/string-check
changed string checking logic
2025-10-11 21:02:44 -05:00
md-yasir 1a2c50b40c changed string checking logic >> string.length() > 0 to !string.isEmpty() 2025-10-11 19:48:33 +05:30
Sean Leary eb97037f7c Merge pull request #1013 from marilynel/master
sonarqube changes to jsonarray
2025-09-24 12:38:56 -05:00
marilynel 05867c4b0b Merge branch 'master' of https://github.com/marilynel/JSON-java 2025-09-21 16:37:20 -08:00
marilynel c6efa080c0 more cleanup sonarqube JSONArray 2025-09-21 16:36:52 -08:00
Sean Leary aff59d06fa Merge pull request #1011 from marilynel/master
more sonarcube fixes
2025-09-18 20:13:43 -05:00
Sean Leary b258ea3d46 Merge pull request #1008 from eleumik/eleumik-patch-1007-array
Update JSONArray.java for #1007
2025-09-18 20:12:55 -05:00
Sean Leary a5e234aa19 Merge pull request #1009 from eleumik/eleumik-patch-1
Update JSONTokener.java for #1007
2025-09-18 20:12:03 -05:00
marilynel f2af220cb4 more sonarcube fixes 2025-09-14 10:59:39 -08:00
Sean Leary a3edc1da0f Merge pull request #1005 from marilynel/master
fixing sonar cube issues
2025-09-11 15:42:48 -05:00
Michele Vivoda 686c084897 Update JSONTokener.java for #1007
fixed parse of `0.` in strict mode
2025-09-10 02:30:19 +02:00
Michele Vivoda 9de3005566 Update JSONArray.java for #1007
fix array content starting with ',' in strict mode
2025-09-10 02:21:16 +02:00
marilynel 69c87dc4db more sonarcube optimization in jsonobject.java 2025-09-07 12:52:59 -08:00
marilynel 53cfa742a7 more sonarcube optimization in jsonobject.java 2025-09-07 12:41:37 -08:00
marilynel 4e0f62b1a6 more sonarcube optimization in jsonobject.java 2025-09-07 12:28:52 -08:00
Sean Leary 9b8eefc2de Merge pull request #1004 from marilynel/master
sonarcube cleanup in JSONObject; more to do
2025-08-29 07:49:28 -05:00
marilynel 6ed2880f55 more sonarcube cleanup 2025-08-24 12:55:49 -08:00
marilynel 9bb26bdb34 sonar cube stuff 2025-08-03 11:52:20 -08:00
Sean Leary 78137d389d Merge pull request #1001 from marilynel/master
addressing sonarqube concerns in JSONObject
2025-07-31 20:54:08 -05:00
marilynel 38c3a0bb3f more sonarcube issues 2025-07-27 11:45:07 -08:00
marilynel ebd9a17a3b addressing minor sonarqube concerns 2025-07-27 11:26:50 -08:00
Sean Leary 82432f0245 Merge pull request #1000 from marilynel/master
fixing sonarcube issues
2025-07-23 20:46:33 -05:00
marilynel e762629bcc oops one more sonarcube issue lol 2025-07-20 12:04:51 -08:00
marilynel 7fc41a6c0e addressing cognitive complextity 2025-07-20 11:58:30 -08:00
marilynel d5d82cdb87 fixing sonarcube issues 2025-07-20 11:31:29 -08:00
Sean Leary 0a9364e920 Merge pull request #999 from marilynel/master
fixed some strict mode issues
2025-07-16 20:12:57 -05:00
marilynel c91b728386 oops forgot null 2025-07-13 12:52:42 -08:00
marilynel fdaeb486ed fixed some strict mode issues 980 2025-07-13 12:41:17 -08:00
Sean Leary f0a78aff61 Merge pull request #995 from marilynel/master
Fix regression XML parsing null with keepStrings
2025-07-09 20:18:48 -05:00
Sean Leary a79e8a15e5 Merge pull request #994 from stleary/tech-debt-20250701
tech-debt-25250701
2025-07-08 11:04:29 -05:00
marilynel 7bb3df8ebf added test details 2025-07-06 12:41:44 -08:00
marilynel 3dce55794f fixed keeping null as string 2025-07-06 12:37:05 -08:00
Sean Leary d7593fb808 Merge pull request #992 from surajdm123/add-tests
Added JUnit test cases for HTTPTokener
2025-07-06 08:27:59 -05:00
Sean Leary 1eed44a59e Merge pull request #993 from surajdm123/add-tests-2
Added JUnit tests for XMLTokenerTest
2025-07-06 08:27:20 -05:00
Sean Leary 7eccadefcd Merge pull request #991 from Simulant87/update-codeql-v3
update CodeQL to v3
2025-07-04 16:39:18 -05:00
Sean Leary 7b0d1942b4 tech-debt-25250701 add jacoco to gradle build, refactor JSONObject to restore performance 2025-07-03 20:39:13 -05:00
surajdm123 a729c2077a Added JUnit tests for XMLTokenerTest 2025-07-03 01:23:46 -07:00
surajdm123 7ac773be72 Added JUnit test cases for HTTPTokener 2025-07-03 00:58:15 -07:00
Simulant 7da120e631 update CodeQL to v3 2025-07-01 22:57:36 +02:00
Sean Leary 197afddbfb Merge pull request #990 from Simulant87/984-refactor-cognitive-complexity-populateMap
Refactor JSONObject populateMap() per SonarQube
2025-07-01 07:13:18 -05:00
Sean Leary 1bdaacc8b0 Merge pull request #989 from AlexCai2019/master
Minor refactoring
2025-06-27 20:17:17 -05:00
Alex Cai c882783d58 Format line 2755 in JSONObject.java 2025-06-27 01:44:27 +08:00
Simulant 5063d314a5 #984 extract method for annotation value check 2025-06-25 23:08:01 +02:00
Simulant 916fba5d39 #984 extract methods reducing cognitive complexity
for JSONObject#populateMap
2025-06-25 23:00:07 +02:00
AlexCai2019 aac376f305 Remove a redundant condition and an empty string
Remove "NULL.equals(object)" on line 2756 of JSONObject.java since line 2752 has already tested it.
Remove the empty string on line 249 of JSONPointer.java.
2025-06-23 01:31:51 +08:00
Sean Leary 32e56da786 Merge pull request #988 from stleary/remove-unused-code-jsonobject
removed unused method from jsonobject
2025-06-16 11:34:35 -05:00
Sean Leary 50330430ce remove-unused-code-jsonobject removed unused method from jsonobject 2025-06-07 16:15:43 -05:00
Sean Leary f1935f5254 Merge pull request #987 from AlexCai2019/master
Use constant.equals()
2025-06-07 09:59:48 -05:00
AlexCai2019 e800cc349f Use constant.equals()
There are some equals() that are not constant.equals(variable), but variable.equals(constant)
2025-06-05 02:15:49 +08:00
Sean Leary 72a1a48173 Merge pull request #983 from harshith8854/master
Use JSONParserConfiguration to decide on serializing Null fields into JSONObject #982
2025-05-31 09:58:46 -05:00
hboggavarapu a381060f81 Add testcase to assert Null fields serialization without JSONParserConfiguration 2025-05-24 21:54:12 +05:30
hboggavarapu dadc3e59dc Use JSONParserConfiguration to decide on serializing null fields into JSONObject #982 2025-05-23 17:57:08 +05:30
Sean Leary 24fafcffeb Merge pull request #981 from stleary/pre-release-20250517
pre-release-20250517 prep for next release
2025-05-17 07:44:38 -05:00
Sean Leary 418d5e9973 pre-release-20250517 prep for next release 2025-05-17 07:41:21 -05:00
Sean Leary 82a02d879e Merge pull request #969 from marilynel/master
refactored large test for strict mode
2025-04-18 11:48:25 -05:00
marilynel 2184ef34d1 refactored large test for strict mode 2025-04-13 11:35:45 -07:00
Sean Leary 8e65eaa992 Merge pull request #968 from marilynel/master
Update keepStrings behavior to reflect changes in keepBooleanAsString, keepNumberAsString
2025-04-10 11:56:36 -05:00
marilynel 74439cf696 Merge branch 'master' of https://github.com/marilynel/JSON-java 2025-04-06 11:05:02 -07:00
marilynel 53da5ce2a9 adjusted keepstrings behavior to reflect changes in keepBooleanAsString & keepNumberAsString 2025-04-06 11:04:33 -07:00
Sean Leary 2e9ad6ff5a Merge pull request #966 from marilynel/master
granular flags to control for keeping boolean or number values as strings
2025-04-04 07:40:55 -05:00
marilynel 8dbf03e76b work on issue 841 2025-03-30 12:21:44 -07:00
Sean Leary 4917e3579d Merge pull request #962 from marilynel/master
Fix: handles edge case 'no \n at end of csv dataset + empty last column'
2025-03-26 20:24:01 -05:00
marilynel 45ec164faa Merge branch 'master' of https://github.com/marilynel/JSON-java 2025-03-23 10:27:57 -07:00
Sean Leary d4c5136c21 Merge pull request #961 from effad/master
Option to store null value in JSONObject when parsing a map
2025-03-23 10:21:53 -05:00
Robert Lichtenberger fd0cca3586 Fix cloning of parser configuration. 2025-03-21 10:12:20 +01:00
Robert Lichtenberger 50a5ce256b Merge branch 'stleary:master' into master 2025-03-21 07:27:12 +01:00
Robert Lichtenberger 1afd7cd6bc Use better name for parser configuration option, fix API comment. 2025-03-21 07:25:37 +01:00
Sean Leary 7751b397bf Merge pull request #960 from marilynel/master
Updated configuration to enable strictMode unit testing with Maven
2025-03-19 11:39:35 -05:00
Robert Lichtenberger 5d1c789490 Add test for JSONArray from Java collection. 2025-03-19 08:10:33 +01:00
Robert Lichtenberger d1327c2da3 Allow to configure Java null handling. 2025-03-19 07:59:57 +01:00
marilynel b2943b8fd0 fixed issue #943 Csv parsing skip last row if last line is missing newline 2025-03-16 12:50:58 -07:00
Marilyn Leary 628d8c42d9 Merge branch 'stleary:master' into master 2025-03-16 10:38:04 -07:00
marilynel 76ee4312b3 readme edit 2025-03-16 10:36:24 -07:00
marilynel 4a662316f7 edited pom.xml for mvn testing with strict mode 2025-03-16 10:33:14 -07:00
Sean Leary 6452a6f38d Merge pull request #955 from marilynel/master
Add testWithStrictMode option to build.gradle
2025-03-05 20:30:24 -06:00
marilynel ae4f4afcc7 dont mess with my line 2025-03-02 11:08:00 -08:00
marilynel 8a86894c63 test with strict mode enabled and fixed 2025-03-02 11:02:27 -08:00
marilynel f30167e7c0 tests seem to be working, run with strictMode = fale then true 2025-02-23 22:00:22 -08:00
Sean Leary 75e5a3d646 Merge pull request #951 from marilynel/master
Fixing and updating unit tests for default strictMode
2025-02-21 07:37:47 -06:00
marilynel 3919abd69a optimized unit tests to respond accurately to default strictMode 2025-02-15 12:30:12 -08:00
marilynel f112a091aa fixed failing unit tests in strict mode, issue 940 2025-02-15 12:03:03 -08:00
Sean Leary 42afb34045 Merge pull request #949 from marilynel/master
deprecated unnecessary setter method
2025-02-15 09:59:56 -06:00
Marilyn Leary a746322e57 Merge branch 'stleary:master' into master 2025-02-09 19:36:46 -08:00
Sean Leary c524cd17a0 Merge pull request #950 from stleary/upgrade-upload-artifact-in-pipeline
upgrade-upload-artifact-in-pipeline update from v3 to v4
2025-02-09 15:01:26 -06:00
Sean Leary 52f249c71e upgrade-upload-artifact-in-pipeline update from v3 to v4 2025-02-09 14:47:18 -06:00
marilynel 1689fc28cf deprecated unnecessary setter method 2025-02-09 11:13:22 -08:00
Sean Leary 22f8290840 Merge pull request #948 from Simulant87/947-JSONTokener-configuration-ignored
use JSONParserConfiguration of JSONTokener in JSONObject and JSONArray constructor instead of creating a new one
2025-01-19 09:09:42 -06:00
Sean Leary 8b857da467 Merge pull request #946 from Simulant87/928-javadoc-warning-JSONParserConfiguration
#928 add missing javaDoc for JSONParserConfiguration
2025-01-19 09:07:53 -06:00
Sean Leary 07b1291448 Merge pull request #942 from michael-ameri/fix-clone
add missing fields when cloning JSONParserConfiguration
2025-01-19 09:06:21 -06:00
Sean Leary 1d81e8879a Merge pull request #938 from Simulant87/remove-references
Strict mode unit tests
2025-01-19 09:03:47 -06:00
Simulant 4c873a1db4 #947 use JSONParserConfiguration of JSONTokener in JSONObject and JSONArray constructor 2025-01-15 21:41:01 +01:00
Simulant 6631b80e8f #947 add new failing tests with JSONTokener having strict mode configuration 2025-01-15 21:38:46 +01:00
Simulant 9218f28db8 #928 add missing java dock for JSONParserConfiguration
(cherry picked from commit afd9a6fbb7)
2025-01-15 21:02:25 +01:00
Simulant 94341cd663 Revert "#928 add missing java dock for JSONParserConfiguration"
This reverts commit afd9a6fbb7.
2025-01-15 20:58:45 +01:00
Simulant afd9a6fbb7 #928 add missing java dock for JSONParserConfiguration 2025-01-15 20:55:13 +01:00
Simulant87 54470e6b56 Merge branch 'stleary:master' into remove-references 2025-01-15 20:48:24 +01:00
Sean Leary dde9d7eceb Merge pull request #931 from stleary/remove-duplicate-moditect
remove-duplicate-moditect: from pom.xml
2025-01-15 07:46:37 -06:00
Sean Leary 8c427d9101 Merge pull request #937 from michael-ameri/remove-references
Update JSONParserConfiguration usage in JSONTokener, JSONArray, and JSONObject
2025-01-15 07:45:50 -06:00
Michael Ameri 4bbbe77446 add missing fields when cloning 2025-01-12 23:03:31 +01:00
Simulant ad44a9274c add new test cases for JSONObject and JSONArray Constructors with JSONTokener and strict mode 2025-01-11 21:43:04 +01:00
Simulant 3b7ba07531 add test for invalid input on JSONTokener 2025-01-11 21:40:41 +01:00
Simulant 215f4268bf add Javadoc and rename parameters to speaking variable names 2025-01-11 21:35:36 +01:00
Michael Ameri ca1c6830c9 remove field references to JSONTokener and JSONParserConfiguration in JSONArray
and JSONObject
2025-01-10 18:05:27 +01:00
Sean Leary 2e153737b1 remove-duplicate-moditect: from pom.xml 2025-01-08 07:33:37 -06:00
55 changed files with 8535 additions and 4993 deletions
-43
View File
@@ -1,43 +0,0 @@
name: "CodeQL"
on:
push:
branches: [ master ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ master ]
schedule:
- cron: '18 18 * * 1'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'java' ]
steps:
- name: Checkout repository
uses: actions/checkout@v3
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
- run: "mvn clean compile -Dmaven.test.skip=true -Dmaven.site.skip=true -Dmaven.javadoc.skip=true"
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
-228
View File
@@ -1,228 +0,0 @@
# This workflow will build a Java project with Maven
# For more information see: https://docs.github.com/en/actions/learn-github-actions or https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions
name: Java CI with Maven
on:
push:
# branches: [ master ]
pull_request:
branches: [ master ]
jobs:
# old-school build and jar method. No tests run or compiled.
build-1_6:
name: Java 1.6
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup java
uses: actions/setup-java@v1
with:
java-version: 1.6
- name: Compile Java 1.6
run: |
mkdir -p target/classes
javac -version
javac -source 1.6 -target 1.6 -d target/classes/ src/main/java/org/json/*.java
- name: Create java 1.6 JAR
run: |
jar cvf target/org.json.jar -C target/classes .
- name: Upload JAR 1.6
if: ${{ always() }}
uses: actions/upload-artifact@v3
with:
name: Create java 1.6 JAR
path: target/*.jar
build-8:
runs-on: ubuntu-latest
strategy:
fail-fast: false
max-parallel: 1
matrix:
# build against supported Java LTS versions:
java: [ 8 ]
name: Java ${{ matrix.java }}
steps:
- uses: actions/checkout@v3
- name: Set up JDK ${{ matrix.java }}
uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: ${{ matrix.java }}
cache: 'maven'
- name: Compile Java ${{ matrix.java }}
run: mvn clean compile -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }} -D maven.test.skip=true -D maven.site.skip=true -D maven.javadoc.skip=true
- name: Run Tests ${{ matrix.java }}
run: |
mvn test -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
- name: Build Test Report ${{ matrix.java }}
if: ${{ always() }}
run: |
mvn surefire-report:report-only -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
mvn site -D generateReports=false -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
- name: Upload Test Results ${{ matrix.java }}
if: ${{ always() }}
uses: actions/upload-artifact@v3
with:
name: Test Results ${{ matrix.java }}
path: target/surefire-reports/
- name: Upload Test Report ${{ matrix.java }}
if: ${{ always() }}
uses: actions/upload-artifact@v3
with:
name: Test Report ${{ matrix.java }}
path: target/site/
- name: Package Jar ${{ matrix.java }}
run: mvn clean package -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }} -D maven.test.skip=true -D maven.site.skip=true
- name: Upload Package Results ${{ matrix.java }}
if: ${{ always() }}
uses: actions/upload-artifact@v3
with:
name: Package Jar ${{ matrix.java }}
path: target/*.jar
build-11:
runs-on: ubuntu-latest
strategy:
fail-fast: false
max-parallel: 1
matrix:
# build against supported Java LTS versions:
java: [ 11 ]
name: Java ${{ matrix.java }}
steps:
- uses: actions/checkout@v3
- name: Set up JDK ${{ matrix.java }}
uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: ${{ matrix.java }}
cache: 'maven'
- name: Compile Java ${{ matrix.java }}
run: mvn clean compile -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }} -D maven.test.skip=true -D maven.site.skip=true -D maven.javadoc.skip=true
- name: Run Tests ${{ matrix.java }}
run: |
mvn test -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
- name: Build Test Report ${{ matrix.java }}
if: ${{ always() }}
run: |
mvn surefire-report:report-only -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
mvn site -D generateReports=false -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
- name: Upload Test Results ${{ matrix.java }}
if: ${{ always() }}
uses: actions/upload-artifact@v3
with:
name: Test Results ${{ matrix.java }}
path: target/surefire-reports/
- name: Upload Test Report ${{ matrix.java }}
if: ${{ always() }}
uses: actions/upload-artifact@v3
with:
name: Test Report ${{ matrix.java }}
path: target/site/
- name: Package Jar ${{ matrix.java }}
run: mvn clean package -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }} -D maven.test.skip=true -D maven.site.skip=true
- name: Upload Package Results ${{ matrix.java }}
if: ${{ always() }}
uses: actions/upload-artifact@v3
with:
name: Package Jar ${{ matrix.java }}
path: target/*.jar
build-17:
runs-on: ubuntu-latest
strategy:
fail-fast: false
max-parallel: 1
matrix:
# build against supported Java LTS versions:
java: [ 17 ]
name: Java ${{ matrix.java }}
steps:
- uses: actions/checkout@v3
- name: Set up JDK ${{ matrix.java }}
uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: ${{ matrix.java }}
cache: 'maven'
- name: Compile Java ${{ matrix.java }}
run: mvn clean compile -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }} -D maven.test.skip=true -D maven.site.skip=true -D maven.javadoc.skip=true
- name: Run Tests ${{ matrix.java }}
run: |
mvn test -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
- name: Build Test Report ${{ matrix.java }}
if: ${{ always() }}
run: |
mvn surefire-report:report-only -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
mvn site -D generateReports=false -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
- name: Upload Test Results ${{ matrix.java }}
if: ${{ always() }}
uses: actions/upload-artifact@v3
with:
name: Test Results ${{ matrix.java }}
path: target/surefire-reports/
- name: Upload Test Report ${{ matrix.java }}
if: ${{ always() }}
uses: actions/upload-artifact@v3
with:
name: Test Report ${{ matrix.java }}
path: target/site/
- name: Package Jar ${{ matrix.java }}
run: mvn clean package -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }} -D maven.test.skip=true -D maven.site.skip=true
- name: Upload Package Results ${{ matrix.java }}
if: ${{ always() }}
uses: actions/upload-artifact@v3
with:
name: Package Jar ${{ matrix.java }}
path: target/*.jar
build-21:
runs-on: ubuntu-latest
strategy:
fail-fast: false
max-parallel: 1
matrix:
# build against supported Java LTS versions:
java: [ 21 ]
name: Java ${{ matrix.java }}
steps:
- uses: actions/checkout@v3
- name: Set up JDK ${{ matrix.java }}
uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: ${{ matrix.java }}
cache: 'maven'
- name: Compile Java ${{ matrix.java }}
run: mvn clean compile -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }} -D maven.test.skip=true -D maven.site.skip=true -D maven.javadoc.skip=true
- name: Run Tests ${{ matrix.java }}
run: |
mvn test -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
- name: Build Test Report ${{ matrix.java }}
if: ${{ always() }}
run: |
mvn surefire-report:report-only -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
mvn site -D generateReports=false -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
- name: Upload Test Results ${{ matrix.java }}
if: ${{ always() }}
uses: actions/upload-artifact@v3
with:
name: Test Results ${{ matrix.java }}
path: target/surefire-reports/
- name: Upload Test Report ${{ matrix.java }}
if: ${{ always() }}
uses: actions/upload-artifact@v3
with:
name: Test Report ${{ matrix.java }}
path: target/site/
- name: Package Jar ${{ matrix.java }}
run: mvn clean package -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }} -D maven.test.skip=true -D maven.site.skip=true
- name: Upload Package Results ${{ matrix.java }}
if: ${{ always() }}
uses: actions/upload-artifact@v3
with:
name: Package Jar ${{ matrix.java }}
path: target/*.jar
+3
View File
@@ -16,3 +16,6 @@ build
/gradlew /gradlew
/gradlew.bat /gradlew.bat
.gitmodules .gitmodules
# ignore compiled class files
*.class
+43
View File
@@ -0,0 +1,43 @@
# Build Instructions
## Building locally
```
mvn clean install
```
GPG signing and Maven Central publishing are only active in the `release` profile, so no GPG key is needed for normal builds.
## Deploying
- **Internal Artifactory** (`https://maven.duxtechnica.org/repository/...`, configured in `distributionManagement`; credentials come from the `internal-release` / `internal-snapshot` server ids in `settings.xml`):
```
mvn clean deploy
```
Versions ending in `-SNAPSHOT` go to the snapshot repo, all others to the release repo.
- **Maven Central** (signed; requires a GPG key and the `central` server id in `settings.xml`):
```
mvn clean deploy -Prelease
```
## GPG signing error (historical)
Before signing was moved to the `release` profile, `mvn clean install` without a GPG key failed with:
```
gpg: no default secret key: No secret key
gpg: signing failed: No secret key
```
### Cause
`maven-gpg-plugin` ran the `sign` goal in the `verify` phase on every build. It now lives in the `release` profile in [pom.xml](./pom.xml), so it only runs with `-Prelease`.
### If you use `-Prelease`
- Check for existing keys: `gpg --list-secret-keys`
- Import a key (`gpg --import private.key`) or generate one (`gpg --gen-key`)
- With multiple keys, select one: `-Dgpg.keyname=<KEYID>`
- The pom passes `--pinentry-mode loopback`, so the passphrase can be supplied with `-Dgpg.passphrase=...`. Prefer `settings.xml` or an environment variable over the command line.
- To run the profile without signing: `-Dgpg.skip=true`
+47 -3
View File
@@ -9,8 +9,9 @@ JSON in Java [package org.json]
[![Maven Central](https://img.shields.io/maven-central/v/org.json/json.svg)](https://mvnrepository.com/artifact/org.json/json) [![Maven Central](https://img.shields.io/maven-central/v/org.json/json.svg)](https://mvnrepository.com/artifact/org.json/json)
[![Java CI with Maven](https://github.com/stleary/JSON-java/actions/workflows/pipeline.yml/badge.svg)](https://github.com/stleary/JSON-java/actions/workflows/pipeline.yml) [![Java CI with Maven](https://github.com/stleary/JSON-java/actions/workflows/pipeline.yml/badge.svg)](https://github.com/stleary/JSON-java/actions/workflows/pipeline.yml)
[![CodeQL](https://github.com/stleary/JSON-java/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/stleary/JSON-java/actions/workflows/codeql-analysis.yml) [![CodeQL](https://github.com/stleary/JSON-java/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/stleary/JSON-java/actions/workflows/codeql-analysis.yml)
[![javadoc](https://javadoc.io/badge2/org.json/json/javadoc.svg)](https://javadoc.io/doc/org.json/json)
**[Click here if you just want the latest release jar file.](https://search.maven.org/remotecontent?filepath=org/json/json/20250107/json-20250107.jar)** **[Click here if you just want the latest release jar file.](https://repo1.maven.org/maven2/org/json/json/20260814/json-20260814.jar)**
# Overview # Overview
@@ -19,6 +20,8 @@ JSON in Java [package org.json]
The JSON-Java package is a reference implementation that demonstrates how to parse JSON documents into Java objects and how to generate new JSON documents from the Java classes. The JSON-Java package is a reference implementation that demonstrates how to parse JSON documents into Java objects and how to generate new JSON documents from the Java classes.
The files in this package implement JSON encoders and decoders. The package can also convert between JSON and XML, HTTP headers, Cookies, and CDL.
Project goals include: Project goals include:
* Reliable and consistent results * Reliable and consistent results
* Adherence to the JSON specification * Adherence to the JSON specification
@@ -26,10 +29,21 @@ Project goals include:
* No external dependencies * No external dependencies
* Fast execution and low memory footprint * Fast execution and low memory footprint
* Maintain backward compatibility * Maintain backward compatibility
* Designed and tested to use on Java versions 1.6 - 21 * Designed and tested to use on Java versions 1.6 - 25
# License Clarification
This project is in the public domain. This means:
* You can use this code for any purpose, including commercial projects
* No attribution or credit is required
* You can modify, distribute, and sublicense freely
* There are no conditions or restrictions whatsoever
The files in this package implement JSON encoders and decoders. The package can also convert between JSON and XML, HTTP headers, Cookies, and CDL. We recognize this can create uncertainty for some corporate legal departments accustomed to standard licenses like MIT or Apache 2.0.
If your organization requires a named license for compliance purposes, public domain is functionally equivalent to the Unlicense or CC0 1.0, both of which have been reviewed and accepted by organizations including the Open Source Initiative and Creative Commons. You may reference either when explaining this project's terms to your legal team.
# Signing keys used in releases
The signing keys can be found in [SECURITY.md](https://github.com/stleary/JSON-java/blob/master/docs/SECURITY.md)
# If you would like to contribute to this project # If you would like to contribute to this project
@@ -37,6 +51,24 @@ For more information on contributions, please see [CONTRIBUTING.md](https://gith
Bug fixes, code improvements, and unit test coverage changes are welcome! Because this project is currently in the maintenance phase, the kinds of changes that can be accepted are limited. For more information, please read the [FAQ](https://github.com/stleary/JSON-java/wiki/FAQ). Bug fixes, code improvements, and unit test coverage changes are welcome! Because this project is currently in the maintenance phase, the kinds of changes that can be accepted are limited. For more information, please read the [FAQ](https://github.com/stleary/JSON-java/wiki/FAQ).
The project has recently received a number of pull requests that each make a small change to existing behavior. Most come from reading the code or a specification, many apparently with the help of AI tools, and not from a problem that someone met in use. Each change is small, but together they put backward compatibility at risk. For that reason, the requirements below now apply.
# Requirements for code changes
These requirements apply to every pull request that changes code under src/main:
**1. File an issue first.** The issue must come from someone who hit the problem in real use. It should describe what you were doing, the input, the result you got, and the result you expected. A difference from a specification that was found by reading the code is not enough on its own.
**2. State which inputs change, and how.** The pull request description must link the issue and list the inputs that behave differently, with the result before and after the change. If no existing behavior changes, say so.
Pull requests that do not meet these requirements may be closed without review.
Pull requests that only change unit tests or documentation do not need an issue. Security vulnerabilities are handled separately; please report them as described in SECURITY.md.
**JSONPointer is frozen**
Several fixes that bring JSONPointer in line with RFC 6901 ship in the release that follows 20260814. Once that release is published, JSONPointer is frozen. It will be reopened only for bugs that users report, under the requirements above. Its behavior is pinned by JSONPointerConformanceTest (**TBD**).
# Build Instructions # Build Instructions
The org.json package can be built from the command line, Maven, and Gradle. The unit tests can be executed from Maven, Gradle, or individually in an IDE e.g. Eclipse. The org.json package can be built from the command line, Maven, and Gradle. The unit tests can be executed from Maven, Gradle, or individually in an IDE e.g. Eclipse.
@@ -97,6 +129,18 @@ Execute the test suite with Gradlew:
gradlew clean build test gradlew clean build test
``` ```
*Optional* Execute the test suite in strict mode with Gradlew:
```shell
gradlew testWithStrictMode
```
*Optional* Execute the test suite in strict mode with Maven:
```shell
mvn test -P test-strict-mode
```
# Notes # Notes
For more information, please see [NOTES.md](https://github.com/stleary/JSON-java/blob/master/docs/NOTES.md) For more information, please see [NOTES.md](https://github.com/stleary/JSON-java/blob/master/docs/NOTES.md)
-5
View File
@@ -1,5 +0,0 @@
# Security Policy
## Reporting a Vulnerability
Please follow the instructions in the ["How are vulnerabilities and exploits handled?"](https://github.com/stleary/JSON-java/wiki/FAQ#how-are-vulnerabilities-and-exploits-handled) section in the FAQ.
+94 -2
View File
@@ -3,9 +3,10 @@
*/ */
apply plugin: 'java' apply plugin: 'java'
apply plugin: 'eclipse' apply plugin: 'eclipse'
// apply plugin: 'jacoco' apply plugin: 'jacoco'
apply plugin: 'maven-publish' apply plugin: 'maven-publish'
// for now, publishing to maven is still a manual process
//plugins { //plugins {
// id 'java' // id 'java'
//id 'maven-publish' //id 'maven-publish'
@@ -19,6 +20,25 @@ repositories {
} }
} }
// To view the report open build/reports/jacoco/test/html/index.html
// Note: disable jacocoTestReport and test blocks, and the jacoco plugin if it interferes with stepping in the debugger
jacocoTestReport {
reports {
html.required = true
}
}
test {
finalizedBy jacocoTestReport
}
// enable logging to stdout during test
tasks.withType(Test) {
testLogging {
showStandardStreams = true
}
}
dependencies { dependencies {
testImplementation 'junit:junit:4.13.2' testImplementation 'junit:junit:4.13.2'
testImplementation 'com.jayway.jsonpath:json-path:2.9.0' testImplementation 'com.jayway.jsonpath:json-path:2.9.0'
@@ -30,7 +50,7 @@ subprojects {
} }
group = 'org.json' group = 'org.json'
version = 'v20250107-SNAPSHOT' version = 'v20260814-SNAPSHOT'
description = 'JSON in Java' description = 'JSON in Java'
sourceCompatibility = '1.8' sourceCompatibility = '1.8'
@@ -53,3 +73,75 @@ publishing {
tasks.withType(JavaCompile) { tasks.withType(JavaCompile) {
options.encoding = 'UTF-8' options.encoding = 'UTF-8'
} }
// Add these imports at the top of your build.gradle file
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.StandardCopyOption
// Your existing build configurations...
// Add a new task to modify the file
task modifyStrictMode {
doLast {
println "Modifying JSONParserConfiguration.java to enable strictMode..."
def filePath = project.file('src/main/java/org/json/JSONParserConfiguration.java')
if (!filePath.exists()) {
throw new GradleException("Could not find file: ${filePath.absolutePath}")
}
// Create a backup of the original file
def backupFile = new File(filePath.absolutePath + '.bak')
Files.copy(filePath.toPath(), backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING)
// Read and modify the file content
def content = filePath.text
def modifiedContent = content.replace('// this.strictMode = true;', 'this.strictMode = true;')
// Write the modified content back to the file
filePath.text = modifiedContent
println "File modified successfully at: ${filePath.absolutePath}"
}
}
// Add a task to restore the original file
task restoreStrictMode {
doLast {
println "Restoring original JSONParserConfiguration.java..."
def filePath = project.file('src/main/java/org/json/JSONParserConfiguration.java')
def backupFile = new File(filePath.absolutePath + '.bak')
if (backupFile.exists()) {
Files.copy(backupFile.toPath(), filePath.toPath(), StandardCopyOption.REPLACE_EXISTING)
backupFile.delete()
println "Original file restored successfully at: ${filePath.absolutePath}"
} else {
println "Backup file not found at: ${backupFile.absolutePath}. No restoration performed."
}
}
}
// Create a task to run the workflow
task testWithStrictMode {
dependsOn modifyStrictMode
finalizedBy restoreStrictMode
doLast {
// This will trigger a clean build and run tests with strictMode enabled
if (org.gradle.internal.os.OperatingSystem.current().isWindows()) {
exec {
executable 'cmd'
args '/c', 'gradlew.bat', 'clean', 'build'
}
} else {
exec {
executable './gradlew'
args 'clean', 'build'
}
}
}
}
+12 -2
View File
@@ -5,9 +5,19 @@ and artifactId "json". For example:
[https://search.maven.org/search?q=g:org.json%20AND%20a:json&core=gav](https://search.maven.org/search?q=g:org.json%20AND%20a:json&core=gav) [https://search.maven.org/search?q=g:org.json%20AND%20a:json&core=gav](https://search.maven.org/search?q=g:org.json%20AND%20a:json&core=gav)
~~~ ~~~
20250107....Restore moditect in pom.xml 20260814 Fixes XML.unescape whitespace handling
20241224....Strict mode opt-in feature, and recent commits. This release does not contain module-info.class. 20260719 Fixes CVE-2026-59171 very large BigInteger, BigDecimal
20260522 Publish key data, recent commits for minor fixes
20251224 Records, fromJson(), and recent commits
20250517 Strict mode hardening and recent commits
20250107 Restore moditect in pom.xml
20241224 Strict mode opt-in feature, and recent commits. This release does not contain module-info.class.
It is not recommended if you need this feature. It is not recommended if you need this feature.
20240303 Revert optLong/getLong changes, and recent commits. 20240303 Revert optLong/getLong changes, and recent commits.
+55
View File
@@ -3,3 +3,58 @@
## Reporting a Vulnerability ## Reporting a Vulnerability
Please follow the instructions in the ["How are vulnerabilities and exploits handled?"](https://github.com/stleary/JSON-java/wiki/FAQ#how-are-vulnerabilities-and-exploits-handled) section in the FAQ. Please follow the instructions in the ["How are vulnerabilities and exploits handled?"](https://github.com/stleary/JSON-java/wiki/FAQ#how-are-vulnerabilities-and-exploits-handled) section in the FAQ.
## Verifying Release Signatures
All releases of `org.json:json` published to Maven Central are signed with PGP. The fingerprint, keyserver location, and verification procedure below let you confirm that the artifacts you've downloaded were produced by this project and have not been modified in transit.
### Signing Key
| | |
| --- | --- |
| **Fingerprint** | `FB35 C8D0 2B47 24DA DA23 DE0A FD11 6C19 69FC CFF3` |
| **Long key ID** | `FD116C1969FCCFF3` |
| **Keyserver** | `hkps://keyserver.ubuntu.com` |
The full 40-character fingerprint above is the canonical identifier for the key. Always pin or compare against the full fingerprint rather than the long or short key ID.
### Importing the Key
```bash
gpg --keyserver hkps://keyserver.ubuntu.com \
--recv-keys FB35C8D02B4724DADA23DE0AFD116C1969FCCFF3
```
After importing, confirm the fingerprint matches what's published here:
```bash
gpg --fingerprint FB35C8D02B4724DADA23DE0AFD116C1969FCCFF3
```
### Verifying an Artifact
Download both the artifact and its detached signature from Maven Central. For example, for version `20251224`:
```bash
curl -O https://repo1.maven.org/maven2/org/json/json/20251224/json-20251224.jar
curl -O https://repo1.maven.org/maven2/org/json/json/20251224/json-20251224.jar.asc
gpg --verify json-20251224.jar.asc json-20251224.jar
```
A successful verification will report `Good signature from ...` and display the same fingerprint shown above. If GPG reports `BAD signature`, a mismatched fingerprint, or `No public key`, do not use the artifact and please open an issue.
The same procedure applies to the `.pom` and any other signed sidecars in the release directory; substitute the filename you want to verify.
### Gradle Dependency Verification
If you are using Gradle's [dependency verification](https://docs.gradle.org/current/userguide/dependency_verification.html) feature, add an entry like the following to `gradle/verification-metadata.xml`:
```xml
<trusted-key id="FB35C8D02B4724DADA23DE0AFD116C1969FCCFF3" group="org.json" name="json"/>
```
Gradle also accepts the long key ID (`FD116C1969FCCFF3`), but pinning the full fingerprint is recommended.
### Key Rotation
If the signing key is ever rotated or revoked, this document will be updated in the `master` branch with the new fingerprint, and the change will be visible in the file's commit history. Always check this file directly in the repository for the current authoritative value before trusting any third-party copy of the fingerprint.
Binary file not shown.
-5
View File
@@ -1,5 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
-183
View File
@@ -1,183 +0,0 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"
Vendored
-103
View File
@@ -1,103 +0,0 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+89 -70
View File
@@ -3,7 +3,7 @@
<groupId>org.json</groupId> <groupId>org.json</groupId>
<artifactId>json</artifactId> <artifactId>json</artifactId>
<version>20250107</version> <version>20260814</version>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>JSON in Java</name> <name>JSON in Java</name>
@@ -46,20 +46,6 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>
<distributionManagement>
<repository>
<id>ossrh</id>
<name>Central Repository OSSRH</name>
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
</repository>
<snapshotRepository>
<id>ossrh</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</snapshotRepository>
</distributionManagement>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
@@ -138,37 +124,6 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
<configuration>
<gpgArguments>
<arg>--pinentry-mode</arg>
<arg>loopback</arg>
</gpgArguments>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.3</version>
<extensions>true</extensions>
<configuration>
<serverId>ossrh</serverId>
<nexusUrl>https://oss.sonatype.org/</nexusUrl>
<autoReleaseAfterClose>false</autoReleaseAfterClose>
</configuration>
</plugin>
<plugin> <plugin>
<groupId>org.moditect</groupId> <groupId>org.moditect</groupId>
<artifactId>moditect-maven-plugin</artifactId> <artifactId>moditect-maven-plugin</artifactId>
@@ -193,30 +148,6 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin>
<groupId>org.moditect</groupId>
<artifactId>moditect-maven-plugin</artifactId>
<version>1.0.0.Final</version>
<executions>
<execution>
<id>add-module-infos</id>
<phase>package</phase>
<goals>
<goal>add-module-info</goal>
</goals>
<configuration>
<jvmVersion>9</jvmVersion>
<module>
<moduleInfoSource>
module org.json {
exports org.json;
}
</moduleInfoSource>
</module>
</configuration>
</execution>
</executions>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
@@ -224,4 +155,92 @@
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<profiles>
<!-- Publishes signed artifacts to Maven Central: mvn -Prelease deploy -->
<profile>
<id>release</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
<configuration>
<gpgArguments>
<arg>--pinentry-mode</arg>
<arg>loopback</arg>
</gpgArguments>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.sonatype.central</groupId>
<artifactId>central-publishing-maven-plugin</artifactId>
<version>0.9.0</version>
<extensions>true</extensions>
<configuration>
<publishingServerId>central</publishingServerId>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>test-strict-mode</id>
<build>
<plugins>
<plugin>
<groupId>com.google.code.maven-replacer-plugin</groupId>
<artifactId>replacer</artifactId>
<version>1.5.3</version>
<executions>
<!-- Enable strict mode -->
<execution>
<id>enable-strict-mode</id>
<phase>process-sources</phase>
<goals>
<goal>replace</goal>
</goals>
<configuration>
<file>src/main/java/org/json/JSONParserConfiguration.java</file>
<replacements>
<replacement>
<token>// this.strictMode = true;</token>
<value>this.strictMode = true;</value>
</replacement>
</replacements>
</configuration>
</execution>
<!-- Restore original code after tests -->
<execution>
<id>restore-original</id>
<phase>test</phase>
<goals>
<goal>replace</goal>
</goals>
<configuration>
<file>src/main/java/org/json/JSONParserConfiguration.java</file>
<replacements>
<replacement>
<token>this.strictMode = true;</token>
<value>// this.strictMode = true;</value>
</replacement>
</replacements>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project> </project>
+80 -21
View File
@@ -27,7 +27,9 @@ public class CDL {
/** /**
* Constructs a new CDL object. * Constructs a new CDL object.
* @deprecated (Utility class cannot be instantiated)
*/ */
@Deprecated
public CDL() { public CDL() {
} }
@@ -100,11 +102,15 @@ public class CDL {
for (;;) { for (;;) {
String value = getValue(x,delimiter); String value = getValue(x,delimiter);
char c = x.next(); char c = x.next();
if (value == null || if (value != null) {
(ja.length() == 0 && value.length() == 0 && c != delimiter)) { ja.put(value);
} else if (ja.length() == 0 && c != delimiter) {
return null; return null;
} else {
// This line accounts for CSV ending with no newline
ja.put("");
} }
ja.put(value);
for (;;) { for (;;) {
if (c == delimiter) { if (c == delimiter) {
break; break;
@@ -177,29 +183,71 @@ public class CDL {
sb.append(delimiter); sb.append(delimiter);
} }
Object object = ja.opt(i); Object object = ja.opt(i);
if (object != null) { appendRowValue(sb, object, delimiter);
String string = object.toString();
if (string.length() > 0 && (string.indexOf(delimiter) >= 0 ||
string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 ||
string.indexOf(0) >= 0 || string.charAt(0) == '"')) {
sb.append('"');
int length = string.length();
for (int j = 0; j < length; j += 1) {
char c = string.charAt(j);
if (c >= ' ' && c != '"') {
sb.append(c);
}
}
sb.append('"');
} else {
sb.append(string);
}
}
} }
sb.append('\n'); sb.append('\n');
return sb.toString(); return sb.toString();
} }
/**
* Append a single row value, quoting it when required by the delimiter or
* content.
*
* @param sb the destination buffer
* @param object the value to append
* @param delimiter the delimiter used between row values
*/
private static void appendRowValue(StringBuilder sb, Object object, char delimiter) {
if (object == null) {
return;
}
String string = object.toString();
if (shouldQuoteValue(string, delimiter)) {
appendQuotedValue(sb, string);
} else {
sb.append(string);
}
}
/**
* Determine whether a row value should be quoted.
*
* @param value the row value to evaluate
* @param delimiter the delimiter used between row values
* @return {@code true} if the value should be quoted
*/
private static boolean shouldQuoteValue(String value, char delimiter) {
if (value.isEmpty()) {
return false;
}
boolean containsDelimiter = value.indexOf(delimiter) >= 0;
boolean containsNewline = value.indexOf('\n') >= 0;
boolean containsCarriageReturn = value.indexOf('\r') >= 0;
boolean containsNullCharacter = value.indexOf(0) >= 0;
boolean startsWithQuote = value.charAt(0) == '"';
return containsDelimiter || containsNewline || containsCarriageReturn ||
containsNullCharacter || startsWithQuote;
}
/**
* Append a row value surrounded by quotes, omitting characters that should
* not appear inside the quoted value.
*
* @param sb the destination buffer
* @param value the value to append
*/
private static void appendQuotedValue(StringBuilder sb, String value) {
sb.append('"');
int length = value.length();
for (int j = 0; j < length; j += 1) {
char c = value.charAt(j);
if (c >= ' ' && c != '"') {
sb.append(c);
}
}
sb.append('"');
}
/** /**
* Produce a JSONArray of JSONObjects from a comma delimited text string, * Produce a JSONArray of JSONObjects from a comma delimited text string,
* using the first row as a source of names. * using the first row as a source of names.
@@ -307,6 +355,17 @@ public class CDL {
if (ja.length() == 0) { if (ja.length() == 0) {
return null; return null;
} }
// The following block accounts for empty datasets (no keys or vals)
if (ja.length() == 1) {
JSONObject j = ja.getJSONObject(0);
if (j.length() == 1) {
String key = j.keys().next();
if ("".equals(key) && "".equals(j.get(key))) {
return null;
}
}
}
return ja; return ja;
} }
+2
View File
@@ -17,7 +17,9 @@ public class Cookie {
/** /**
* Constructs a new Cookie object. * Constructs a new Cookie object.
* @deprecated (Utility class cannot be instantiated)
*/ */
@Deprecated()
public Cookie() { public Cookie() {
} }
+2
View File
@@ -13,7 +13,9 @@ public class CookieList {
/** /**
* Constructs a new CookieList object. * Constructs a new CookieList object.
* @deprecated (Utility class cannot be instantiated)
*/ */
@Deprecated
public CookieList() { public CookieList() {
} }
+204 -134
View File
@@ -67,12 +67,6 @@ public class JSONArray implements Iterable<Object> {
*/ */
private final ArrayList<Object> myArrayList; private final ArrayList<Object> myArrayList;
// strict mode checks after constructor require access to this object
private JSONTokener jsonTokener;
// strict mode checks after constructor require access to this object
private JSONParserConfiguration jsonParserConfiguration;
/** /**
* Construct an empty JSONArray. * Construct an empty JSONArray.
*/ */
@@ -86,84 +80,119 @@ public class JSONArray implements Iterable<Object> {
* @param x * @param x
* A JSONTokener * A JSONTokener
* @throws JSONException * @throws JSONException
* If there is a syntax error. * If there is a syntax error.
*/ */
public JSONArray(JSONTokener x) throws JSONException { public JSONArray(JSONTokener x) throws JSONException {
this(x, new JSONParserConfiguration()); this(x, x.getJsonParserConfiguration());
} }
/** /**
* Constructs a JSONArray from a JSONTokener and a JSONParserConfiguration. * Constructs a JSONArray from a JSONTokener and a JSONParserConfiguration.
* The supplied configuration applies to all values during construction,
* including nested objects and arrays. The tokener's original configuration
* is restored afterward, even if parsing fails.
* *
* @param x A JSONTokener instance from which the JSONArray is constructed. * @param x A JSONTokener instance from which the JSONArray is constructed.
* @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser. * @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser.
* @throws JSONException If a syntax error occurs during the construction of the JSONArray. * @throws JSONException If a syntax error occurs during the construction of the JSONArray.
*/ */
public JSONArray(JSONTokener x, JSONParserConfiguration jsonParserConfiguration) throws JSONException { public JSONArray(JSONTokener x, JSONParserConfiguration jsonParserConfiguration) throws JSONException {
this(x, jsonParserConfiguration, true);
}
/**
* Constructs a JSONArray from a JSONTokener and a JSONParserConfiguration, for internal use. <br>
* Never call this instead of using withStrictMode(boolean).
*
* @param x A JSONTokener instance from which the JSONArray is constructed.
* @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser.
* @param isInitial A boolean that determines whether this array is the root.
* @throws JSONException If a syntax error occurs during the construction of the JSONArray.
*/
JSONArray(JSONTokener x, JSONParserConfiguration jsonParserConfiguration, boolean isInitial) throws JSONException {
this(); this();
JSONParserConfiguration originalConfiguration = x.getJsonParserConfiguration();
x.setJsonParserConfigurationInternal(jsonParserConfiguration);
try {
if (x.nextClean() != '[') {
throw x.syntaxError("A JSONArray text must start with '['");
}
if (this.jsonParserConfiguration == null) { char nextChar = x.nextClean();
this.jsonParserConfiguration = jsonParserConfiguration; if (nextChar == 0) {
} // array is unclosed. No ']' found, instead EOF
if (this.jsonTokener == null) { throw x.syntaxError("Expected a ',' or ']'");
this.jsonTokener = x; } else if (nextChar==',' && jsonParserConfiguration.isStrictMode()) {
this.jsonTokener.setJsonParserConfiguration(this.jsonParserConfiguration); throw x.syntaxError("Array content starts with a ','");
} }
if (nextChar != ']') {
if (x.nextClean() != '[') { x.back();
throw x.syntaxError("A JSONArray text must start with '['"); for (;;) {
} if (x.nextClean() == ',') {
x.back();
char nextChar = x.nextClean(); this.myArrayList.add(JSONObject.NULL);
if (nextChar == 0) { } else {
// array is unclosed. No ']' found, instead EOF x.back();
throw x.syntaxError("Expected a ',' or ']'"); this.myArrayList.add(x.nextValue());
} }
if (nextChar != ']') { if (checkForSyntaxError(x, jsonParserConfiguration, isInitial)) return;
x.back();
for (;;) {
if (x.nextClean() == ',') {
x.back();
this.myArrayList.add(JSONObject.NULL);
} else {
x.back();
this.myArrayList.add(x.nextValue());
} }
switch (x.nextClean()) { } else {
case 0: if (isInitial && jsonParserConfiguration.isStrictMode() && x.nextClean() != 0) {
// array is unclosed. No ']' found, instead EOF throw x.syntaxError("Strict mode error: Unparsed characters found at end of input text");
throw x.syntaxError("Expected a ',' or ']'");
case ',':
nextChar = x.nextClean();
if (nextChar == 0) {
// array is unclosed. No ']' found, instead EOF
throw x.syntaxError("Expected a ',' or ']'");
}
if (nextChar == ']') {
// trailing commas are not allowed in strict mode
if (jsonParserConfiguration.isStrictMode()) {
throw x.syntaxError("Strict mode error: Expected another array element");
}
return;
}
if (nextChar == ',') {
// consecutive commas are not allowed in strict mode
if (jsonParserConfiguration.isStrictMode()) {
throw x.syntaxError("Strict mode error: Expected a valid array element");
}
return;
}
x.back();
break;
case ']':
return;
default:
throw x.syntaxError("Expected a ',' or ']'");
} }
} }
} finally {
x.setJsonParserConfigurationInternal(originalConfiguration);
} }
} }
/** Convenience function. Checks for JSON syntax error.
* @param x A JSONTokener instance from which the JSONArray is constructed.
* @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser.
* @param isInitial Boolean indicating position of char
* @return true if a syntax error has occurred, otherwise false
*/
private boolean checkForSyntaxError(JSONTokener x, JSONParserConfiguration jsonParserConfiguration, boolean isInitial) {
char nextChar;
switch (x.nextClean()) {
case 0:
// array is unclosed. No ']' found, instead EOF
throw x.syntaxError("Expected a ',' or ']'");
case ',':
nextChar = x.nextClean();
if (nextChar == 0) {
// array is unclosed. No ']' found, instead EOF
throw x.syntaxError("Expected a ',' or ']'");
}
if (nextChar == ']') {
// trailing commas are not allowed in strict mode
if (jsonParserConfiguration.isStrictMode()) {
throw x.syntaxError("Strict mode error: Expected another array element");
}
return true;
}
if (nextChar == ',') {
// Consecutive commas are not allowed in strict mode.
// Otherwise, the tokener is backed up, and a null object is inserted by the calling code.
if (jsonParserConfiguration.isStrictMode()) {
throw x.syntaxError("Strict mode error: Expected a valid array element");
}
}
x.back();
break;
case ']':
if (isInitial && jsonParserConfiguration.isStrictMode() &&
x.nextClean() != 0) {
throw x.syntaxError("Strict mode error: Unparsed characters found at end of input text");
}
return true;
default:
throw x.syntaxError("Expected a ',' or ']'");
}
return false;
}
/** /**
* Construct a JSONArray from a source JSON text. * Construct a JSONArray from a source JSON text.
* *
@@ -176,11 +205,6 @@ public class JSONArray implements Iterable<Object> {
*/ */
public JSONArray(String source) throws JSONException { public JSONArray(String source) throws JSONException {
this(source, new JSONParserConfiguration()); this(source, new JSONParserConfiguration());
// Strict mode does not allow trailing chars
if (this.jsonParserConfiguration.isStrictMode() &&
this.jsonTokener.nextClean() != 0) {
throw jsonTokener.syntaxError("Strict mode error: Unparsed characters found at end of input text");
}
} }
/** /**
@@ -195,12 +219,7 @@ public class JSONArray implements Iterable<Object> {
* If there is a syntax error. * If there is a syntax error.
*/ */
public JSONArray(String source, JSONParserConfiguration jsonParserConfiguration) throws JSONException { public JSONArray(String source, JSONParserConfiguration jsonParserConfiguration) throws JSONException {
this(new JSONTokener(source), jsonParserConfiguration); this(new JSONTokener(source, jsonParserConfiguration), jsonParserConfiguration);
// Strict mode does not allow trailing chars
if (this.jsonParserConfiguration.isStrictMode() &&
this.jsonTokener.nextClean() != 0) {
throw jsonTokener.syntaxError("Strict mode error: Unparsed characters found at end of input text");
}
} }
/** /**
@@ -349,13 +368,11 @@ public class JSONArray implements Iterable<Object> {
*/ */
public boolean getBoolean(int index) throws JSONException { public boolean getBoolean(int index) throws JSONException {
Object object = this.get(index); Object object = this.get(index);
if (object.equals(Boolean.FALSE) if (Boolean.FALSE.equals(object)
|| (object instanceof String && ((String) object) || (object instanceof String && "false".equalsIgnoreCase((String) object))) {
.equalsIgnoreCase("false"))) {
return false; return false;
} else if (object.equals(Boolean.TRUE) } else if (Boolean.TRUE.equals(object)
|| (object instanceof String && ((String) object) || (object instanceof String && "true".equalsIgnoreCase((String) object))) {
.equalsIgnoreCase("true"))) {
return true; return true;
} }
throw wrongValueFormatException(index, "boolean", object, null); throw wrongValueFormatException(index, "boolean", object, null);
@@ -486,8 +503,29 @@ public class JSONArray implements Iterable<Object> {
* to a BigInteger. * to a BigInteger.
*/ */
public BigInteger getBigInteger (int index) throws JSONException { public BigInteger getBigInteger (int index) throws JSONException {
return this.getBigInteger(index, new JSONParserConfiguration());
}
/**
* Get the BigInteger value associated with an index.
*
* @param index
* The index must be between 0 and length() - 1.
* @param jsonParserConfiguration
* A configuration whose {@code maxNumberLength} bounds the number of
* decimal digits in the returned integer. Values exceeding this length
* are treated as unconvertible. Pass a configuration with
* {@link ParserConfiguration#UNDEFINED_MAXIMUM_NUMBER_LENGTH} to disable
* this check.
* @return The value.
* @throws JSONException
* If the key is not found or if the value cannot be converted
* to a BigInteger.
*/
public BigInteger getBigInteger (int index, JSONParserConfiguration jsonParserConfiguration)
throws JSONException {
Object object = this.get(index); Object object = this.get(index);
BigInteger val = JSONObject.objectToBigInteger(object, null); BigInteger val = JSONObject.objectToBigInteger(object, null, jsonParserConfiguration);
if(val == null) { if(val == null) {
throw wrongValueFormatException(index, "BigInteger", object, null); throw wrongValueFormatException(index, "BigInteger", object, null);
} }
@@ -750,11 +788,7 @@ public class JSONArray implements Iterable<Object> {
if (val == null) { if (val == null) {
return defaultValue; return defaultValue;
} }
final double doubleValue = val.doubleValue(); return val.doubleValue();
// if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) {
// return defaultValue;
// }
return doubleValue;
} }
/** /**
@@ -786,11 +820,7 @@ public class JSONArray implements Iterable<Object> {
if (val == null) { if (val == null) {
return defaultValue; return defaultValue;
} }
final Double doubleValue = val.doubleValue(); return val.doubleValue();
// if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) {
// return defaultValue;
// }
return doubleValue;
} }
/** /**
@@ -822,11 +852,7 @@ public class JSONArray implements Iterable<Object> {
if (val == null) { if (val == null) {
return defaultValue; return defaultValue;
} }
final float floatValue = val.floatValue(); return val.floatValue();
// if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) {
// return floatValue;
// }
return floatValue;
} }
/** /**
@@ -858,11 +884,7 @@ public class JSONArray implements Iterable<Object> {
if (val == null) { if (val == null) {
return defaultValue; return defaultValue;
} }
final Float floatValue = val.floatValue(); return val.floatValue();
// if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) {
// return floatValue;
// }
return floatValue;
} }
/** /**
@@ -979,8 +1001,8 @@ public class JSONArray implements Iterable<Object> {
} }
/** /**
* Get the optional BigInteger value associated with an index. The * Get the optional BigInteger value associated with an index. The
* defaultValue is returned if there is no value for the index, or if the * defaultValue is returned if there is no value for the index, or if the
* value is not a number and cannot be converted to a number. * value is not a number and cannot be converted to a number.
* *
* @param index * @param index
@@ -990,8 +1012,31 @@ public class JSONArray implements Iterable<Object> {
* @return The value. * @return The value.
*/ */
public BigInteger optBigInteger(int index, BigInteger defaultValue) { public BigInteger optBigInteger(int index, BigInteger defaultValue) {
return this.optBigInteger(index, defaultValue, new JSONParserConfiguration());
}
/**
* Get the optional BigInteger value associated with an index. The
* defaultValue is returned if there is no value for the index, or if the
* value is not a number and cannot be converted to a number.
*
* @param index
* The index must be between 0 and length() - 1.
* @param defaultValue
* The default value.
* @param jsonParserConfiguration
* A configuration whose {@code maxNumberLength} bounds the number of
* decimal digits in the returned integer. Values exceeding this length
* are treated as unconvertible and {@code defaultValue} is returned.
* Pass a configuration with
* {@link ParserConfiguration#UNDEFINED_MAXIMUM_NUMBER_LENGTH} to disable
* this check.
* @return The value.
*/
public BigInteger optBigInteger(int index, BigInteger defaultValue,
JSONParserConfiguration jsonParserConfiguration) {
Object val = this.opt(index); Object val = this.opt(index);
return JSONObject.objectToBigInteger(val, defaultValue); return JSONObject.objectToBigInteger(val, defaultValue, jsonParserConfiguration);
} }
/** /**
@@ -1660,29 +1705,44 @@ public class JSONArray implements Iterable<Object> {
if(valueThis == null) { if(valueThis == null) {
return false; return false;
} }
if (valueThis instanceof JSONObject) { if (!isSimilar(valueThis, valueOther)) {
if (!((JSONObject)valueThis).similar(valueOther)) {
return false;
}
} else if (valueThis instanceof JSONArray) {
if (!((JSONArray)valueThis).similar(valueOther)) {
return false;
}
} else if (valueThis instanceof Number && valueOther instanceof Number) {
if (!JSONObject.isNumberSimilar((Number)valueThis, (Number)valueOther)) {
return false;
}
} else if (valueThis instanceof JSONString && valueOther instanceof JSONString) {
if (!((JSONString) valueThis).toJSONString().equals(((JSONString) valueOther).toJSONString())) {
return false;
}
} else if (!valueThis.equals(valueOther)) {
return false; return false;
} }
} }
return true; return true;
} }
/**
* Convenience function; checks for object similarity
* @param valueThis
* Initial object to compare
* @param valueOther
* Comparison object
* @return boolean
*/
private boolean isSimilar(Object valueThis, Object valueOther) {
if (valueThis instanceof JSONObject) {
if (!((JSONObject)valueThis).similar(valueOther)) {
return false;
}
} else if (valueThis instanceof JSONArray) {
if (!((JSONArray)valueThis).similar(valueOther)) {
return false;
}
} else if (valueThis instanceof Number && valueOther instanceof Number) {
if (!JSONObject.isNumberSimilar((Number)valueThis, (Number)valueOther)) {
return false;
}
} else if (valueThis instanceof JSONString && valueOther instanceof JSONString) {
if (!((JSONString) valueThis).toJSONString().equals(((JSONString) valueOther).toJSONString())) {
return false;
}
} else if (!valueThis.equals(valueOther)) {
return false;
}
return true;
}
/** /**
* Produce a JSONObject by combining a JSONArray of names with the values of * Produce a JSONObject by combining a JSONArray of names with the values of
* this JSONArray. * this JSONArray.
@@ -1814,12 +1874,7 @@ public class JSONArray implements Iterable<Object> {
writer.write('['); writer.write('[');
if (length == 1) { if (length == 1) {
try { writeArrayAttempt(writer, indentFactor, indent, 0);
JSONObject.writeValue(writer, this.myArrayList.get(0),
indentFactor, indent);
} catch (Exception e) {
throw new JSONException("Unable to write JSONArray value at index: 0", e);
}
} else if (length != 0) { } else if (length != 0) {
final int newIndent = indent + indentFactor; final int newIndent = indent + indentFactor;
@@ -1831,12 +1886,7 @@ public class JSONArray implements Iterable<Object> {
writer.write('\n'); writer.write('\n');
} }
JSONObject.indent(writer, newIndent); JSONObject.indent(writer, newIndent);
try { writeArrayAttempt(writer, indentFactor, newIndent, i);
JSONObject.writeValue(writer, this.myArrayList.get(i),
indentFactor, newIndent);
} catch (Exception e) {
throw new JSONException("Unable to write JSONArray value at index: " + i, e);
}
needsComma = true; needsComma = true;
} }
if (indentFactor > 0) { if (indentFactor > 0) {
@@ -1851,6 +1901,26 @@ public class JSONArray implements Iterable<Object> {
} }
} }
/**
* Convenience function. Attempts to write
* @param writer
* Writes the serialized JSON
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @param indent
* The indentation of the top level.
* @param i
* Index in array to be added
*/
private void writeArrayAttempt(Writer writer, int indentFactor, int indent, int i) {
try {
JSONObject.writeValue(writer, this.myArrayList.get(i),
indentFactor, indent);
} catch (Exception e) {
throw new JSONException("Unable to write JSONArray value at index: " + i, e);
}
}
/** /**
* Returns a java.util.List containing all of the elements in this array. * Returns a java.util.List containing all of the elements in this array.
* If an element in the array is a JSONArray or JSONObject it will also * If an element in the array is a JSONArray or JSONObject it will also
+64 -20
View File
@@ -14,12 +14,44 @@ Public Domain.
*/ */
public class JSONML { public class JSONML {
private static final String CHILD_NODES = "childNodes";
/** /**
* Constructs a new JSONML object. * Constructs a new JSONML object.
* @deprecated (Utility class cannot be instantiated)
*/ */
@Deprecated
public JSONML() { public JSONML() {
} }
/**
* Safely cast parse result to JSONArray with proper type checking.
* @param result The result from parse() method
* @return JSONArray if result is a JSONArray
* @throws JSONException if result is not a JSONArray
*/
private static JSONArray toJSONArraySafe(Object result) throws JSONException {
if (result instanceof JSONArray) {
return (JSONArray) result;
}
throw new JSONException("Expected JSONArray but got " +
(result == null ? "null" : result.getClass().getSimpleName()));
}
/**
* Safely cast parse result to JSONObject with proper type checking.
* @param result The result from parse() method
* @return JSONObject if result is a JSONObject
* @throws JSONException if result is not a JSONObject
*/
private static JSONObject toJSONObjectSafe(Object result) throws JSONException {
if (result instanceof JSONObject) {
return (JSONObject) result;
}
throw new JSONException("Expected JSONObject but got " +
(result == null ? "null" : result.getClass().getSimpleName()));
}
/** /**
* Parse XML values and store them in a JSONArray. * Parse XML values and store them in a JSONArray.
* @param x The XMLTokener containing the source string. * @param x The XMLTokener containing the source string.
@@ -111,7 +143,7 @@ public class JSONML {
} }
} else if (c == '[') { } else if (c == '[') {
token = x.nextToken(); token = x.nextToken();
if (token.equals("CDATA") && x.next() == '[') { if ("CDATA".equals(token) && x.next() == '[') {
if (ja != null) { if (ja != null) {
ja.put(x.nextCDATA()); ja.put(x.nextCDATA());
} }
@@ -175,7 +207,7 @@ public class JSONML {
// attribute = value // attribute = value
attribute = (String)token; attribute = (String)token;
if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) { if (!arrayForm && ("tagName".equals(attribute) || CHILD_NODES.equals(attribute))) {
throw x.syntaxError("Reserved attribute."); throw x.syntaxError("Reserved attribute.");
} }
token = x.nextToken(); token = x.nextToken();
@@ -226,7 +258,7 @@ public class JSONML {
} }
tagName = null; tagName = null;
if (!arrayForm && newja.length() > 0) { if (!arrayForm && newja.length() > 0) {
newjo.put("childNodes", newja); newjo.put(CHILD_NODES, newja);
} }
if (ja == null) { if (ja == null) {
if (arrayForm) { if (arrayForm) {
@@ -239,9 +271,21 @@ public class JSONML {
} }
} else { } else {
if (ja != null) { if (ja != null) {
ja.put(token instanceof String Object value;
? (config.isKeepStrings() ? XML.unescape((String)token) : XML.stringToValue((String)token))
: token); if (token instanceof String) {
String strToken = (String) token;
if (config.isKeepStrings()) {
value = strToken;
} else {
value = XML.stringToValue(strToken);
}
} else {
value = token;
}
ja.put(value);
} }
} }
} }
@@ -261,7 +305,7 @@ public class JSONML {
* @throws JSONException Thrown on error converting to a JSONArray * @throws JSONException Thrown on error converting to a JSONArray
*/ */
public static JSONArray toJSONArray(String string) throws JSONException { public static JSONArray toJSONArray(String string) throws JSONException {
return (JSONArray)parse(new XMLTokener(string), true, null, JSONMLParserConfiguration.ORIGINAL, 0); return toJSONArraySafe(parse(new XMLTokener(string), true, null, JSONMLParserConfiguration.ORIGINAL, 0));
} }
@@ -283,7 +327,7 @@ public class JSONML {
* @throws JSONException Thrown on error converting to a JSONArray * @throws JSONException Thrown on error converting to a JSONArray
*/ */
public static JSONArray toJSONArray(String string, boolean keepStrings) throws JSONException { public static JSONArray toJSONArray(String string, boolean keepStrings) throws JSONException {
return (JSONArray)parse(new XMLTokener(string), true, null, keepStrings, 0); return toJSONArraySafe(parse(new XMLTokener(string), true, null, keepStrings, 0));
} }
@@ -308,7 +352,7 @@ public class JSONML {
* @throws JSONException Thrown on error converting to a JSONArray * @throws JSONException Thrown on error converting to a JSONArray
*/ */
public static JSONArray toJSONArray(String string, JSONMLParserConfiguration config) throws JSONException { public static JSONArray toJSONArray(String string, JSONMLParserConfiguration config) throws JSONException {
return (JSONArray)parse(new XMLTokener(string), true, null, config, 0); return toJSONArraySafe(parse(new XMLTokener(string), true, null, config, 0));
} }
@@ -332,7 +376,7 @@ public class JSONML {
* @throws JSONException Thrown on error converting to a JSONArray * @throws JSONException Thrown on error converting to a JSONArray
*/ */
public static JSONArray toJSONArray(XMLTokener x, JSONMLParserConfiguration config) throws JSONException { public static JSONArray toJSONArray(XMLTokener x, JSONMLParserConfiguration config) throws JSONException {
return (JSONArray)parse(x, true, null, config, 0); return toJSONArraySafe(parse(x, true, null, config, 0));
} }
@@ -354,7 +398,7 @@ public class JSONML {
* @throws JSONException Thrown on error converting to a JSONArray * @throws JSONException Thrown on error converting to a JSONArray
*/ */
public static JSONArray toJSONArray(XMLTokener x, boolean keepStrings) throws JSONException { public static JSONArray toJSONArray(XMLTokener x, boolean keepStrings) throws JSONException {
return (JSONArray)parse(x, true, null, keepStrings, 0); return toJSONArraySafe(parse(x, true, null, keepStrings, 0));
} }
@@ -371,7 +415,7 @@ public class JSONML {
* @throws JSONException Thrown on error converting to a JSONArray * @throws JSONException Thrown on error converting to a JSONArray
*/ */
public static JSONArray toJSONArray(XMLTokener x) throws JSONException { public static JSONArray toJSONArray(XMLTokener x) throws JSONException {
return (JSONArray)parse(x, true, null, false, 0); return toJSONArraySafe(parse(x, true, null, false, 0));
} }
@@ -389,7 +433,7 @@ public class JSONML {
* @throws JSONException Thrown on error converting to a JSONObject * @throws JSONException Thrown on error converting to a JSONObject
*/ */
public static JSONObject toJSONObject(String string) throws JSONException { public static JSONObject toJSONObject(String string) throws JSONException {
return (JSONObject)parse(new XMLTokener(string), false, null, false, 0); return toJSONObjectSafe(parse(new XMLTokener(string), false, null, false, 0));
} }
@@ -409,7 +453,7 @@ public class JSONML {
* @throws JSONException Thrown on error converting to a JSONObject * @throws JSONException Thrown on error converting to a JSONObject
*/ */
public static JSONObject toJSONObject(String string, boolean keepStrings) throws JSONException { public static JSONObject toJSONObject(String string, boolean keepStrings) throws JSONException {
return (JSONObject)parse(new XMLTokener(string), false, null, keepStrings, 0); return toJSONObjectSafe(parse(new XMLTokener(string), false, null, keepStrings, 0));
} }
@@ -431,7 +475,7 @@ public class JSONML {
* @throws JSONException Thrown on error converting to a JSONObject * @throws JSONException Thrown on error converting to a JSONObject
*/ */
public static JSONObject toJSONObject(String string, JSONMLParserConfiguration config) throws JSONException { public static JSONObject toJSONObject(String string, JSONMLParserConfiguration config) throws JSONException {
return (JSONObject)parse(new XMLTokener(string), false, null, config, 0); return toJSONObjectSafe(parse(new XMLTokener(string), false, null, config, 0));
} }
@@ -449,7 +493,7 @@ public class JSONML {
* @throws JSONException Thrown on error converting to a JSONObject * @throws JSONException Thrown on error converting to a JSONObject
*/ */
public static JSONObject toJSONObject(XMLTokener x) throws JSONException { public static JSONObject toJSONObject(XMLTokener x) throws JSONException {
return (JSONObject)parse(x, false, null, false, 0); return toJSONObjectSafe(parse(x, false, null, false, 0));
} }
@@ -469,7 +513,7 @@ public class JSONML {
* @throws JSONException Thrown on error converting to a JSONObject * @throws JSONException Thrown on error converting to a JSONObject
*/ */
public static JSONObject toJSONObject(XMLTokener x, boolean keepStrings) throws JSONException { public static JSONObject toJSONObject(XMLTokener x, boolean keepStrings) throws JSONException {
return (JSONObject)parse(x, false, null, keepStrings, 0); return toJSONObjectSafe(parse(x, false, null, keepStrings, 0));
} }
@@ -491,7 +535,7 @@ public class JSONML {
* @throws JSONException Thrown on error converting to a JSONObject * @throws JSONException Thrown on error converting to a JSONObject
*/ */
public static JSONObject toJSONObject(XMLTokener x, JSONMLParserConfiguration config) throws JSONException { public static JSONObject toJSONObject(XMLTokener x, JSONMLParserConfiguration config) throws JSONException {
return (JSONObject)parse(x, false, null, config, 0); return toJSONObjectSafe(parse(x, false, null, config, 0));
} }
@@ -606,7 +650,7 @@ public class JSONML {
// Don't use the new entrySet API to maintain Android support // Don't use the new entrySet API to maintain Android support
for (final String key : jo.keySet()) { for (final String key : jo.keySet()) {
if (!"tagName".equals(key) && !"childNodes".equals(key)) { if (!"tagName".equals(key) && !CHILD_NODES.equals(key)) {
XML.noSpace(key); XML.noSpace(key);
value = jo.opt(key); value = jo.opt(key);
if (value != null) { if (value != null) {
@@ -622,7 +666,7 @@ public class JSONML {
//Emit content in body //Emit content in body
ja = jo.optJSONArray("childNodes"); ja = jo.optJSONArray(CHILD_NODES);
if (ja == null) { if (ja == null) {
sb.append('/'); sb.append('/');
sb.append('>'); sb.append('>');
File diff suppressed because it is too large Load Diff
@@ -4,10 +4,30 @@ package org.json;
* Configuration object for the JSON parser. The configuration is immutable. * Configuration object for the JSON parser. The configuration is immutable.
*/ */
public class JSONParserConfiguration extends ParserConfiguration { public class JSONParserConfiguration extends ParserConfiguration {
/**
* The default maximum number of distinct object keys shared within one parse.
*/
public static final int DEFAULT_MAXIMUM_SHARED_KEYS = 1000;
/**
* Used to indicate that there is no limit on the number of distinct object keys shared within one parse.
*/
public static final int UNLIMITED_SHARED_KEYS = -1;
/** /**
* Used to indicate whether to overwrite duplicate key or not. * Used to indicate whether to overwrite duplicate key or not.
*/ */
private boolean overwriteDuplicateKey; private boolean overwriteDuplicateKey;
/**
* Used to indicate whether to convert java null values to JSONObject.NULL or ignoring the entry when converting java maps.
*/
private boolean useNativeNulls;
/**
* The maximum number of distinct object keys shared within one parse.
*/
private int maxSharedKeys;
/** /**
* Configuration with the default values. * Configuration with the default values.
@@ -15,6 +35,9 @@ public class JSONParserConfiguration extends ParserConfiguration {
public JSONParserConfiguration() { public JSONParserConfiguration() {
super(); super();
this.overwriteDuplicateKey = false; this.overwriteDuplicateKey = false;
this.maxSharedKeys = DEFAULT_MAXIMUM_SHARED_KEYS;
// DO NOT DELETE THE FOLLOWING LINE -- it is used for strictMode testing
// this.strictMode = true;
} }
/** /**
@@ -27,7 +50,11 @@ public class JSONParserConfiguration extends ParserConfiguration {
protected JSONParserConfiguration clone() { protected JSONParserConfiguration clone() {
JSONParserConfiguration clone = new JSONParserConfiguration(); JSONParserConfiguration clone = new JSONParserConfiguration();
clone.overwriteDuplicateKey = overwriteDuplicateKey; clone.overwriteDuplicateKey = overwriteDuplicateKey;
clone.strictMode = strictMode;
clone.maxNestingDepth = maxNestingDepth; clone.maxNestingDepth = maxNestingDepth;
clone.keepStrings = keepStrings;
clone.useNativeNulls = useNativeNulls;
clone.maxSharedKeys = maxSharedKeys;
return clone; return clone;
} }
@@ -63,6 +90,39 @@ public class JSONParserConfiguration extends ParserConfiguration {
return clone; return clone;
} }
/**
* Controls the parser's behavior when meeting Java null values while converting maps.
* If set to true, the parser will put a JSONObject.NULL into the resulting JSONObject.
* Or the map entry will be ignored.
*
* @param useNativeNulls defines if the parser should convert null values in Java maps
* @return The existing configuration will not be modified. A new configuration is returned.
*/
public JSONParserConfiguration withUseNativeNulls(final boolean useNativeNulls) {
JSONParserConfiguration clone = this.clone();
clone.useNativeNulls = useNativeNulls;
return clone;
}
/**
* Defines how many distinct object keys the parser shares within one parse. When a key repeats, for example
* in each element of an array of objects, the parser reuses the first String instance read for that key
* instead of keeping a separate copy in every object. Only the first <code>maxSharedKeys</code> distinct keys
* are shared, so input that begins with many unique keys may need a higher limit. The default is 1000.
* Parsed values are the same with any setting.
*
* @param maxSharedKeys the maximum number of distinct keys to share; 0 disables sharing, and
* {@link #UNLIMITED_SHARED_KEYS} (or any negative value) removes the limit
* @return The existing configuration will not be modified. A new configuration is returned.
*/
public JSONParserConfiguration withMaxSharedKeys(final int maxSharedKeys) {
JSONParserConfiguration clone = this.clone();
clone.maxSharedKeys = Math.max(maxSharedKeys, UNLIMITED_SHARED_KEYS);
return clone;
}
/** /**
* Sets the strict mode configuration for the JSON parser with default true value * Sets the strict mode configuration for the JSON parser with default true value
@@ -102,8 +162,33 @@ public class JSONParserConfiguration extends ParserConfiguration {
public boolean isOverwriteDuplicateKey() { public boolean isOverwriteDuplicateKey() {
return this.overwriteDuplicateKey; return this.overwriteDuplicateKey;
} }
/**
* The parser's behavior when meeting a null value in a java map, controls whether the parser should
* write a JSON entry with a null value (<code>isUseNativeNulls() == true</code>)
* or ignore that map entry (<code>isUseNativeNulls() == false</code>).
*
* @return The <code>useNativeNulls</code> configuration value.
*/
public boolean isUseNativeNulls() {
return this.useNativeNulls;
}
/** /**
* The maximum number of distinct object keys shared within one parse. 0 means keys are not shared,
* and {@link #UNLIMITED_SHARED_KEYS} means there is no limit.
*
* @return The <code>maxSharedKeys</code> configuration value.
*/
public int getMaxSharedKeys() {
return this.maxSharedKeys;
}
/**
* The parser throws an Exception when strict mode is true and tries to parse invalid JSON characters.
* Otherwise, the parser is more relaxed and might tolerate some invalid characters.
*
* @return the current strict mode setting. * @return the current strict mode setting.
*/ */
public boolean isStrictMode() { public boolean isStrictMode() {
+6 -5
View File
@@ -127,7 +127,7 @@ public class JSONPointer {
if (pointer == null) { if (pointer == null) {
throw new NullPointerException("pointer cannot be null"); throw new NullPointerException("pointer cannot be null");
} }
if (pointer.isEmpty() || pointer.equals("#")) { if (pointer.isEmpty() || "#".equals(pointer)) {
this.refTokens = Collections.emptyList(); this.refTokens = Collections.emptyList();
return; return;
} }
@@ -135,7 +135,8 @@ public class JSONPointer {
if (pointer.startsWith("#/")) { if (pointer.startsWith("#/")) {
refs = pointer.substring(2); refs = pointer.substring(2);
try { try {
refs = URLDecoder.decode(refs, ENCODING); // URI fragments preserve plus signs rather than treating them as form-encoded spaces.
refs = URLDecoder.decode(refs.replace("+", "%2B"), ENCODING);
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@@ -203,7 +204,7 @@ public class JSONPointer {
Object current = document; Object current = document;
for (String token : this.refTokens) { for (String token : this.refTokens) {
if (current instanceof JSONObject) { if (current instanceof JSONObject) {
current = ((JSONObject) current).opt(unescape(token)); current = ((JSONObject) current).opt(token);
} else if (current instanceof JSONArray) { } else if (current instanceof JSONArray) {
current = readByIndexToken(current, token); current = readByIndexToken(current, token);
} else { } else {
@@ -246,7 +247,7 @@ public class JSONPointer {
*/ */
@Override @Override
public String toString() { public String toString() {
StringBuilder rval = new StringBuilder(""); StringBuilder rval = new StringBuilder();
for (String token: this.refTokens) { for (String token: this.refTokens) {
rval.append('/').append(escape(token)); rval.append('/').append(escape(token));
} }
@@ -276,7 +277,7 @@ public class JSONPointer {
try { try {
StringBuilder rval = new StringBuilder("#"); StringBuilder rval = new StringBuilder("#");
for (String token : this.refTokens) { for (String token : this.refTokens) {
rval.append('/').append(URLEncoder.encode(token, ENCODING)); rval.append('/').append(URLEncoder.encode(escape(token), ENCODING).replace("+", "%20"));
} }
return rval.toString(); return rval.toString();
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
+92 -13
View File
@@ -2,6 +2,8 @@ package org.json;
import java.io.*; import java.io.*;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
/* /*
Public Domain. Public Domain.
@@ -35,12 +37,27 @@ public class JSONTokener {
// access to this object is required for strict mode checking // access to this object is required for strict mode checking
private JSONParserConfiguration jsonParserConfiguration; private JSONParserConfiguration jsonParserConfiguration;
/** object keys already read, so repeated keys can share one String instance. */
private Map<String, String> sharedKeys;
/** /**
* Construct a JSONTokener from a Reader. The caller must close the Reader. * Construct a JSONTokener from a Reader. The caller must close the Reader.
* *
* @param reader A reader. * @param reader the source.
*/ */
public JSONTokener(Reader reader) { public JSONTokener(Reader reader) {
this(reader, new JSONParserConfiguration());
}
/**
* Construct a JSONTokener from a Reader with a given JSONParserConfiguration. The caller must close the Reader.
*
* @param reader the source.
* @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser.
*
*/
public JSONTokener(Reader reader, JSONParserConfiguration jsonParserConfiguration) {
this.jsonParserConfiguration = jsonParserConfiguration;
this.reader = reader.markSupported() this.reader = reader.markSupported()
? reader ? reader
: new BufferedReader(reader); : new BufferedReader(reader);
@@ -53,23 +70,40 @@ public class JSONTokener {
this.line = 1; this.line = 1;
} }
/** /**
* Construct a JSONTokener from an InputStream. The caller must close the input stream. * Construct a JSONTokener from an InputStream. The caller must close the input stream.
* @param inputStream The source. * @param inputStream The source.
*/ */
public JSONTokener(InputStream inputStream) { public JSONTokener(InputStream inputStream) {
this(new InputStreamReader(inputStream, Charset.forName("UTF-8"))); this(inputStream, new JSONParserConfiguration());
}
/**
* Construct a JSONTokener from an InputStream. The caller must close the input stream.
* @param inputStream The source.
* @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser.
*/
public JSONTokener(InputStream inputStream, JSONParserConfiguration jsonParserConfiguration) {
this(new InputStreamReader(inputStream, Charset.forName("UTF-8")), jsonParserConfiguration);
} }
/** /**
* Construct a JSONTokener from a string. * Construct a JSONTokener from a string.
* *
* @param s A source string. * @param source A source string.
*/ */
public JSONTokener(String s) { public JSONTokener(String source) {
this(new StringReader(s)); this(new StringReader(source));
}
/**
* Construct a JSONTokener from an InputStream. The caller must close the input stream.
* @param source The source.
* @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser.
*/
public JSONTokener(String source, JSONParserConfiguration jsonParserConfiguration) {
this(new StringReader(source), jsonParserConfiguration);
} }
/** /**
@@ -83,11 +117,43 @@ public class JSONTokener {
/** /**
* Setter * Setter
* @param jsonParserConfiguration new value for jsonParserConfiguration * @param jsonParserConfiguration new value for jsonParserConfiguration
*
* @deprecated method should not be used
*/ */
@Deprecated
public void setJsonParserConfiguration(JSONParserConfiguration jsonParserConfiguration) { public void setJsonParserConfiguration(JSONParserConfiguration jsonParserConfiguration) {
setJsonParserConfigurationInternal(jsonParserConfiguration);
}
void setJsonParserConfigurationInternal(JSONParserConfiguration jsonParserConfiguration) {
this.jsonParserConfiguration = jsonParserConfiguration; this.jsonParserConfiguration = jsonParserConfiguration;
} }
/**
* Returns an earlier String instance equal to the key if this tokener has read one, otherwise the key itself.
*
* @param key an object key that was just read
* @param maxSharedKeys the maximum number of distinct keys to remember; 0 disables sharing and a negative
* value means no limit
* @return a String equal to <code>key</code>
*/
String shareKey(String key, int maxSharedKeys) {
if (maxSharedKeys == 0) {
return key;
}
if (this.sharedKeys == null) {
this.sharedKeys = new HashMap<String, String>();
}
String shared = this.sharedKeys.get(key);
if (shared != null) {
return shared;
}
if (maxSharedKeys < 0 || this.sharedKeys.size() < maxSharedKeys) {
this.sharedKeys.put(key, key);
}
return key;
}
/** /**
* Back up one character. This provides a sort of lookahead capability, * Back up one character. This provides a sort of lookahead capability,
* so that you can test for a digit or letter before attempting to parse * so that you can test for a digit or letter before attempting to parse
@@ -426,14 +492,14 @@ public class JSONTokener {
case '{': case '{':
this.back(); this.back();
try { try {
return new JSONObject(this, jsonParserConfiguration); return new JSONObject(this, jsonParserConfiguration, false);
} catch (StackOverflowError e) { } catch (StackOverflowError e) {
throw new JSONException("JSON Array or Object depth too large to process.", e); throw new JSONException("JSON Array or Object depth too large to process.", e);
} }
case '[': case '[':
this.back(); this.back();
try { try {
return new JSONArray(this, jsonParserConfiguration); return new JSONArray(this, jsonParserConfiguration, false);
} catch (StackOverflowError e) { } catch (StackOverflowError e) {
throw new JSONException("JSON Array or Object depth too large to process.", e); throw new JSONException("JSON Array or Object depth too large to process.", e);
} }
@@ -477,13 +543,26 @@ public class JSONTokener {
string = sb.toString().trim(); string = sb.toString().trim();
if ("".equals(string)) { if ("".equals(string)) {
throw this.syntaxError("Missing value"); throw this.syntaxError("Missing value");
} else if (jsonParserConfiguration != null &&
jsonParserConfiguration.isStrictMode() && string.endsWith(".")) {
throw this.syntaxError(String.format("Strict mode error: Value '%s' ends with dot", string));
} }
Object obj = JSONObject.stringToValue(string); Object obj = JSONObject.stringToValue(string, jsonParserConfiguration);
// Strict mode only allows strings with explicit double quotes // if obj is a boolean, look at string
if (jsonParserConfiguration != null && if (jsonParserConfiguration != null &&
jsonParserConfiguration.isStrictMode() && jsonParserConfiguration.isStrictMode()) {
obj instanceof String) { if (obj instanceof Boolean && !"true".equals(string) && !"false".equals(string)) {
throw this.syntaxError(String.format("Strict mode error: Value '%s' is not surrounded by quotes", obj)); // Strict mode only allows lowercase true or false
throw this.syntaxError(String.format("Strict mode error: Value '%s' is not lowercase boolean", obj));
}
else if (obj == JSONObject.NULL && !"null".equals(string)) {
// Strint mode only allows lowercase null
throw this.syntaxError(String.format("Strict mode error: Value '%s' is not lowercase null", obj));
}
else if (obj instanceof String) {
// Strict mode only allows strings with explicit double quotes
throw this.syntaxError(String.format("Strict mode error: Value '%s' is not surrounded by quotes", obj));
}
} }
return obj; return obj;
} }
@@ -13,11 +13,21 @@ public class ParserConfiguration {
*/ */
public static final int UNDEFINED_MAXIMUM_NESTING_DEPTH = -1; public static final int UNDEFINED_MAXIMUM_NESTING_DEPTH = -1;
/**
* Used to indicate there's no defined limit to the maximum number length
*/
public static final int UNDEFINED_MAXIMUM_NUMBER_LENGTH = -1;
/** /**
* The default maximum nesting depth when parsing a document. * The default maximum nesting depth when parsing a document.
*/ */
public static final int DEFAULT_MAXIMUM_NESTING_DEPTH = 512; public static final int DEFAULT_MAXIMUM_NESTING_DEPTH = 512;
/**
* The default max number length
*/
public static final int DEFAULT_MAX_NUMBER_LENGTH = 1000;
/** /**
* Specifies if values should be kept as strings (<code>true</code>), or if * Specifies if values should be kept as strings (<code>true</code>), or if
* they should try to be guessed into JSON values (numeric, boolean, string). * they should try to be guessed into JSON values (numeric, boolean, string).
@@ -29,23 +39,32 @@ public class ParserConfiguration {
*/ */
protected int maxNestingDepth; protected int maxNestingDepth;
/**
* The max number of chars for any number. Exceeding this limit will cause the value to be converted to a string
*/
protected int maxNumberLength;
/** /**
* Constructs a new ParserConfiguration with default settings. * Constructs a new ParserConfiguration with default settings.
*/ */
public ParserConfiguration() { public ParserConfiguration() {
this.keepStrings = false; this.keepStrings = false;
this.maxNestingDepth = DEFAULT_MAXIMUM_NESTING_DEPTH; this.maxNestingDepth = DEFAULT_MAXIMUM_NESTING_DEPTH;
this.maxNumberLength = DEFAULT_MAX_NUMBER_LENGTH;
} }
/** /**
* Constructs a new ParserConfiguration with the specified settings. * Constructs a new ParserConfiguration with the specified settings. Use the with* methods instead of calling this ctor.
* *
* @param keepStrings A boolean indicating whether to preserve strings during parsing. * @param keepStrings A boolean indicating whether to preserve strings during parsing.
* @param maxNestingDepth An integer representing the maximum allowed nesting depth. * @param maxNestingDepth An integer representing the maximum allowed nesting depth.
* @deprecated Use the with*() methods instead
*/ */
@Deprecated
protected ParserConfiguration(final boolean keepStrings, final int maxNestingDepth) { protected ParserConfiguration(final boolean keepStrings, final int maxNestingDepth) {
this.keepStrings = keepStrings; this.keepStrings = keepStrings;
this.maxNestingDepth = maxNestingDepth; this.maxNestingDepth = maxNestingDepth;
this.maxNumberLength = DEFAULT_MAX_NUMBER_LENGTH;
} }
/** /**
@@ -58,10 +77,11 @@ public class ParserConfiguration {
// item, a new map instance should be created and if possible each value in the // item, a new map instance should be created and if possible each value in the
// map should be cloned as well. If the values of the map are known to also // map should be cloned as well. If the values of the map are known to also
// be immutable, then a shallow clone of the map is acceptable. // be immutable, then a shallow clone of the map is acceptable.
return new ParserConfiguration( ParserConfiguration parserConfiguration = new ParserConfiguration();
this.keepStrings, parserConfiguration.keepStrings = this.keepStrings;
this.maxNestingDepth parserConfiguration.maxNestingDepth = this.maxNestingDepth;
); parserConfiguration.maxNumberLength = this.maxNumberLength;
return parserConfiguration;
} }
/** /**
@@ -123,4 +143,37 @@ public class ParserConfiguration {
return newConfig; return newConfig;
} }
/**
* The maximum number length that the parser will allow
*
* @return the maximum number lengtj set for this configuration
*/
public int getMaxNumberLength() {
return maxNumberLength;
}
/**
* Defines the maximum number length that the parser will allow
* Using any negative value as a parameter is equivalent to setting no limit to the length
* which means any size number is allowed
*
* @param maxNumberLength the maximum number length allowed
* @param <T> the type of the configuration object
* @return The existing configuration will not be modified. A new configuration is returned.
*/
@SuppressWarnings("unchecked")
public <T extends ParserConfiguration> T withMaxNumberLength(int maxNumberLength) {
T newConfig = (T) this.clone();
if (maxNumberLength > UNDEFINED_MAXIMUM_NUMBER_LENGTH) {
newConfig.maxNumberLength = maxNumberLength;
} else {
newConfig.maxNumberLength = UNDEFINED_MAXIMUM_NUMBER_LENGTH;
}
return newConfig;
}
} }
+1 -1
View File
@@ -30,7 +30,7 @@ public class Property {
// can't use the new constructor for Android support // can't use the new constructor for Android support
// JSONObject jo = new JSONObject(properties == null ? 0 : properties.size()); // JSONObject jo = new JSONObject(properties == null ? 0 : properties.size());
JSONObject jo = new JSONObject(); JSONObject jo = new JSONObject();
if (properties != null && !properties.isEmpty()) { if (properties != null) {
Enumeration<?> enumProperties = properties.propertyNames(); Enumeration<?> enumProperties = properties.propertyNames();
while(enumProperties.hasMoreElements()) { while(enumProperties.hasMoreElements()) {
String name = (String)enumProperties.nextElement(); String name = (String)enumProperties.nextElement();
+204 -28
View File
@@ -9,6 +9,7 @@ import java.io.StringReader;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.BigInteger; import java.math.BigInteger;
import java.util.Iterator; import java.util.Iterator;
import java.util.NoSuchElementException;
/** /**
* This provides static methods to convert an XML text into a JSONObject, and to * This provides static methods to convert an XML text into a JSONObject, and to
@@ -80,7 +81,7 @@ public class XML {
public Iterator<Integer> iterator() { public Iterator<Integer> iterator() {
return new Iterator<Integer>() { return new Iterator<Integer>() {
private int nextIndex = 0; private int nextIndex = 0;
private int length = string.length(); private final int length = string.length();
@Override @Override
public boolean hasNext() { public boolean hasNext() {
@@ -89,6 +90,9 @@ public class XML {
@Override @Override
public Integer next() { public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
int result = string.codePointAt(this.nextIndex); int result = string.codePointAt(this.nextIndex);
this.nextIndex += Character.charCount(result); this.nextIndex += Character.charCount(result);
return result; return result;
@@ -152,28 +156,45 @@ public class XML {
/** /**
* @param cp code point to test * @param cp code point to test
* @return true if the code point is not valid for an XML * @return true if the code point must be escaped when serializing to XML
*/ */
private static boolean mustEscape(int cp) { static boolean mustEscape(int cp) {
// Every ISO control character must be written as a numeric character
// reference when serializing. This includes #x9 (tab), #xA (LF) and
// #xD (CR): literal occurrences of these characters are subject to
// whitespace normalization by conforming XML parsers, so they can
// only survive a round trip as &#9;, &#10; and &#13; (see #1092).
//
// This method is only about the serialization path. Numeric character
// references found while parsing are validated with
// isValidXmlCharacter(int) (see #1059).
return Character.isISOControl(cp) || !isValidXmlCharacter(cp);
}
/**
* @param cp code point to test
* @return true if the code point can be written as a numeric character
* reference in a document generated by this class
*/
static boolean isValidXmlCharacter(int cp) {
/* Valid range from https://www.w3.org/TR/REC-xml/#charsets /* Valid range from https://www.w3.org/TR/REC-xml/#charsets
* *
* #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] * #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
* *
* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. * any Unicode character, excluding the surrogate blocks, FFFE, and FFFF.
*/ */
// isISOControl is true when (cp >= 0 && cp <= 0x1F) || (cp >= 0x7F && cp <= 0x9F) // The C1 control characters (#x7F-#x9F) fall inside [#x20-#xD7FF] and
// all ISO control characters are out of range except tabs and new lines // are therefore legal XML 1.0 characters, but this class has always
return (Character.isISOControl(cp) // rejected &#NN; references to them while parsing. Keeping them
&& cp != 0x9 // rejected here keeps the parse result of this fix identical to the
&& cp != 0xA // previous release; accepting them would be a separate behaviour
&& cp != 0xD // change (see #1093).
) || !( if (Character.isISOControl(cp)) {
// valid the range of acceptable characters that aren't control return cp == 0x9 || cp == 0xA || cp == 0xD;
(cp >= 0x20 && cp <= 0xD7FF) }
|| (cp >= 0xE000 && cp <= 0xFFFD) return (cp >= 0x20 && cp <= 0xD7FF)
|| (cp >= 0x10000 && cp <= 0x10FFFF) || (cp >= 0xE000 && cp <= 0xFFFD)
) || (cp >= 0x10000 && cp <= 0x10FFFF);
;
} }
/** /**
@@ -228,6 +249,28 @@ public class XML {
} }
} }
/**
* Throw an exception if the string contains an XML metacharacter
* ({@code < > & " ' /}). Used by {@link #toString(Object)} to reject JSON
* keys that would otherwise be emitted verbatim between {@code <} and
* {@code >} and could break out of the tag context (element injection,
* CWE-91; see issue #1071).
*
* @param string the candidate element name
* @throws JSONException if {@code string} contains an XML metacharacter
*/
static void noXmlMetachars(String string) throws JSONException {
int length = string.length();
for (int i = 0; i < length; i++) {
char c = string.charAt(i);
if (c == '<' || c == '>' || c == '&'
|| c == '"' || c == '\'' || c == '/') {
throw new JSONException("'" + string
+ "' contains an XML metacharacter and may not be used as an element name.");
}
}
}
/** /**
* Scan the content following the named tag, attaching it to the context. * Scan the content following the named tag, attaching it to the context.
* *
@@ -355,10 +398,20 @@ public class XML {
&& TYPE_ATTR.equals(string)) { && TYPE_ATTR.equals(string)) {
xmlXsiTypeConverter = config.getXsiTypeMap().get(token); xmlXsiTypeConverter = config.getXsiTypeMap().get(token);
} else if (!nilAttributeFound) { } else if (!nilAttributeFound) {
jsonObject.accumulate(string, Object obj = stringToValue((String) token);
config.isKeepStrings() if (obj instanceof Boolean) {
? ((String) token) jsonObject.accumulate(string,
: stringToValue((String) token)); config.isKeepBooleanAsString()
? ((String) token)
: obj);
} else if (obj instanceof Number) {
jsonObject.accumulate(string,
config.isKeepNumberAsString()
? ((String) token)
: obj);
} else {
jsonObject.accumulate(string, stringToValue((String) token));
}
} }
token = null; token = null;
} else { } else {
@@ -377,8 +430,13 @@ public class XML {
context.append(tagName, JSONObject.NULL); context.append(tagName, JSONObject.NULL);
} else if (jsonObject.length() > 0) { } else if (jsonObject.length() > 0) {
context.append(tagName, jsonObject); context.append(tagName, jsonObject);
} else { } else if(context.isEmpty()) { //avoids resetting the array in case of an empty tag in the middle or end
context.put(tagName, new JSONArray()); context.put(tagName, new JSONArray());
if (jsonObject.isEmpty()){
context.append(tagName, "");
}
} else {
context.append(tagName, "");
} }
} else { } else {
if (nilAttributeFound) { if (nilAttributeFound) {
@@ -407,8 +465,23 @@ public class XML {
jsonObject.accumulate(config.getcDataTagName(), jsonObject.accumulate(config.getcDataTagName(),
stringToValue(string, xmlXsiTypeConverter)); stringToValue(string, xmlXsiTypeConverter));
} else { } else {
jsonObject.accumulate(config.getcDataTagName(), Object obj = stringToValue((String) token);
config.isKeepStrings() ? string : stringToValue(string)); if (obj instanceof Boolean) {
jsonObject.accumulate(config.getcDataTagName(),
config.isKeepBooleanAsString()
? ((String) token)
: obj);
} else if (obj instanceof Number) {
jsonObject.accumulate(config.getcDataTagName(),
config.isKeepNumberAsString()
? ((String) token)
: obj);
} else if (obj == JSONObject.NULL) {
jsonObject.accumulate(config.getcDataTagName(),
config.isKeepStrings() ? ((String) token) : obj);
} else {
jsonObject.accumulate(config.getcDataTagName(), stringToValue((String) token));
}
} }
} }
@@ -422,7 +495,11 @@ public class XML {
if (config.getForceList().contains(tagName)) { if (config.getForceList().contains(tagName)) {
// Force the value to be an array // Force the value to be an array
if (jsonObject.length() == 0) { if (jsonObject.length() == 0) {
context.put(tagName, new JSONArray()); //avoids resetting the array in case of an empty element in the middle or end
if(context.isEmpty()) {
context.put(tagName, new JSONArray());
}
context.append(tagName, "");
} else if (jsonObject.length() == 1 } else if (jsonObject.length() == 1
&& jsonObject.opt(config.getcDataTagName()) != null) { && jsonObject.opt(config.getcDataTagName()) != null) {
context.append(tagName, jsonObject.opt(config.getcDataTagName())); context.append(tagName, jsonObject.opt(config.getcDataTagName()));
@@ -581,14 +658,30 @@ public class XML {
/** /**
* This method is the same as {@link JSONObject#stringToValue(String)}. * This method is the same as {@link JSONObject#stringToValue(String)}.
* * Warning! stringToValue(String) uses the default max number length. If you want to override it,
* @param string String to convert * use a suitable initialized XMLParserConfiguration and the method: stringToValue(String, XMLParserConfiguration).
* @param str String to convert
* @return JSON value of this string or the string * @return JSON value of this string or the string
*/ */
// To maintain compatibility with the Android API, this method is a direct copy of // To maintain compatibility with the Android API, this method is a direct copy of
// the one in JSONObject. Changes made here should be reflected there. // the one in JSONObject. Changes made here should be reflected there.
// This method should not make calls out of the XML object. // This method should not make calls out of the XML object.
public static Object stringToValue(String string) { public static Object stringToValue(String str) {
return stringToValue(str, new XMLParserConfiguration());
}
/**
* This method is the same as {@link JSONObject#stringToValue(String)}.
*
* @param string String to convert
* @param xmlParserConfiguration the XML parser config object
* @return JSON value of this string or the string. If the string represents a number that is too large,
* a string will be returned.
*/
// To maintain compatibility with the Android API, this method is a direct copy of
// the one in JSONObject. Changes made here should be reflected there.
// This method should not make calls out of the XML object.
public static Object stringToValue(String string, XMLParserConfiguration xmlParserConfiguration) {
if ("".equals(string)) { if ("".equals(string)) {
return string; return string;
} }
@@ -612,7 +705,13 @@ public class XML {
char initial = string.charAt(0); char initial = string.charAt(0);
if ((initial >= '0' && initial <= '9') || initial == '-') { if ((initial >= '0' && initial <= '9') || initial == '-') {
try { try {
return stringToNumber(string); // user declines max number checking
if (xmlParserConfiguration.getMaxNumberLength() == ParserConfiguration.UNDEFINED_MAXIMUM_NUMBER_LENGTH) {
return stringToNumber(string);
}
if(string.length() <= xmlParserConfiguration.getMaxNumberLength()) {
return stringToNumber(string);
}
} catch (Exception ignore) { } catch (Exception ignore) {
} }
} }
@@ -688,6 +787,44 @@ public class XML {
return toJSONObject(reader, XMLParserConfiguration.ORIGINAL); return toJSONObject(reader, XMLParserConfiguration.ORIGINAL);
} }
/**
* Convert a well-formed (but not necessarily valid) XML into a
* JSONObject. Some information may be lost in this transformation because
* JSON is a data format and XML is a document format. XML uses elements,
* attributes, and content text, while JSON uses unordered collections of
* name/value pairs and arrays of values. JSON does not does not like to
* distinguish between elements and attributes. Sequences of similar
* elements are represented as JSONArrays. Content text may be placed in a
* "content" member. Comments, prologs, DTDs, and <pre>{@code
* &lt;[ [ ]]>}</pre>
* are ignored.
*
* All numbers are converted as strings, for 1, 01, 29.0 will not be coerced to
* numbers but will instead be the exact value as seen in the XML document depending
* on how flag is set.
* All booleans are converted as strings, for true, false will not be coerced to
* booleans but will instead be the exact value as seen in the XML document depending
* on how flag is set.
*
* @param reader The XML source reader.
* @param keepNumberAsString If true, then numeric values will not be coerced into
* numeric values and will instead be left as strings
* @param keepBooleanAsString If true, then boolean values will not be coerced into
* * numeric values and will instead be left as strings
* @return A JSONObject containing the structured data from the XML string.
* @throws JSONException Thrown if there is an errors while parsing the string
*/
public static JSONObject toJSONObject(Reader reader, boolean keepNumberAsString, boolean keepBooleanAsString) throws JSONException {
XMLParserConfiguration xmlParserConfiguration = new XMLParserConfiguration();
if(keepNumberAsString) {
xmlParserConfiguration = xmlParserConfiguration.withKeepNumberAsString(keepNumberAsString);
}
if(keepBooleanAsString) {
xmlParserConfiguration = xmlParserConfiguration.withKeepBooleanAsString(keepBooleanAsString);
}
return toJSONObject(reader, xmlParserConfiguration);
}
/** /**
* Convert a well-formed (but not necessarily valid) XML into a * Convert a well-formed (but not necessarily valid) XML into a
* JSONObject. Some information may be lost in this transformation because * JSONObject. Some information may be lost in this transformation because
@@ -746,6 +883,38 @@ public class XML {
return toJSONObject(new StringReader(string), keepStrings); return toJSONObject(new StringReader(string), keepStrings);
} }
/**
* Convert a well-formed (but not necessarily valid) XML string into a
* JSONObject. Some information may be lost in this transformation because
* JSON is a data format and XML is a document format. XML uses elements,
* attributes, and content text, while JSON uses unordered collections of
* name/value pairs and arrays of values. JSON does not does not like to
* distinguish between elements and attributes. Sequences of similar
* elements are represented as JSONArrays. Content text may be placed in a
* "content" member. Comments, prologs, DTDs, and <pre>{@code
* &lt;[ [ ]]>}</pre>
* are ignored.
*
* All numbers are converted as strings, for 1, 01, 29.0 will not be coerced to
* numbers but will instead be the exact value as seen in the XML document depending
* on how flag is set.
* All booleans are converted as strings, for true, false will not be coerced to
* booleans but will instead be the exact value as seen in the XML document depending
* on how flag is set.
*
* @param string
* The source string.
* @param keepNumberAsString If true, then numeric values will not be coerced into
* numeric values and will instead be left as strings
* @param keepBooleanAsString If true, then boolean values will not be coerced into
* numeric values and will instead be left as strings
* @return A JSONObject containing the structured data from the XML string.
* @throws JSONException Thrown if there is an errors while parsing the string
*/
public static JSONObject toJSONObject(String string, boolean keepNumberAsString, boolean keepBooleanAsString) throws JSONException {
return toJSONObject(new StringReader(string), keepNumberAsString, keepBooleanAsString);
}
/** /**
* Convert a well-formed (but not necessarily valid) XML string into a * Convert a well-formed (but not necessarily valid) XML string into a
* JSONObject. Some information may be lost in this transformation because * JSONObject. Some information may be lost in this transformation because
@@ -838,6 +1007,10 @@ public class XML {
JSONObject jo; JSONObject jo;
String string; String string;
if (tagName != null) {
noXmlMetachars(tagName);
}
if (object instanceof JSONObject) { if (object instanceof JSONObject) {
// Emit <tagName> // Emit <tagName>
@@ -856,6 +1029,9 @@ public class XML {
// don't use the new entrySet accessor to maintain Android Support // don't use the new entrySet accessor to maintain Android Support
jo = (JSONObject) object; jo = (JSONObject) object;
for (final String key : jo.keySet()) { for (final String key : jo.keySet()) {
if (!key.equals(config.getcDataTagName())) {
noXmlMetachars(key);
}
Object value = jo.opt(key); Object value = jo.opt(key);
if (value == null) { if (value == null) {
value = ""; value = "";
@@ -22,6 +22,16 @@ public class XMLParserConfiguration extends ParserConfiguration {
*/ */
// public static final int DEFAULT_MAXIMUM_NESTING_DEPTH = 512; // We could override // public static final int DEFAULT_MAXIMUM_NESTING_DEPTH = 512; // We could override
/**
* Allow user to control how numbers are parsed
*/
private boolean keepNumberAsString;
/**
* Allow user to control how booleans are parsed
*/
private boolean keepBooleanAsString;
/** Original Configuration of the XML Parser. */ /** Original Configuration of the XML Parser. */
public static final XMLParserConfiguration ORIGINAL public static final XMLParserConfiguration ORIGINAL
= new XMLParserConfiguration(); = new XMLParserConfiguration();
@@ -142,7 +152,9 @@ public class XMLParserConfiguration extends ParserConfiguration {
*/ */
@Deprecated @Deprecated
public XMLParserConfiguration (final boolean keepStrings, final String cDataTagName, final boolean convertNilAttributeToNull) { public XMLParserConfiguration (final boolean keepStrings, final String cDataTagName, final boolean convertNilAttributeToNull) {
super(keepStrings, DEFAULT_MAXIMUM_NESTING_DEPTH); super(false, DEFAULT_MAXIMUM_NESTING_DEPTH);
this.keepNumberAsString = keepStrings;
this.keepBooleanAsString = keepStrings;
this.cDataTagName = cDataTagName; this.cDataTagName = cDataTagName;
this.convertNilAttributeToNull = convertNilAttributeToNull; this.convertNilAttributeToNull = convertNilAttributeToNull;
} }
@@ -163,8 +175,10 @@ public class XMLParserConfiguration extends ParserConfiguration {
*/ */
private XMLParserConfiguration (final boolean keepStrings, final String cDataTagName, private XMLParserConfiguration (final boolean keepStrings, final String cDataTagName,
final boolean convertNilAttributeToNull, final Map<String, XMLXsiTypeConverter<?>> xsiTypeMap, final Set<String> forceList, final boolean convertNilAttributeToNull, final Map<String, XMLXsiTypeConverter<?>> xsiTypeMap, final Set<String> forceList,
final int maxNestingDepth, final boolean closeEmptyTag) { final int maxNestingDepth, final boolean closeEmptyTag, final boolean keepNumberAsString, final boolean keepBooleanAsString) {
super(keepStrings, maxNestingDepth); super(false, maxNestingDepth);
this.keepNumberAsString = keepNumberAsString;
this.keepBooleanAsString = keepBooleanAsString;
this.cDataTagName = cDataTagName; this.cDataTagName = cDataTagName;
this.convertNilAttributeToNull = convertNilAttributeToNull; this.convertNilAttributeToNull = convertNilAttributeToNull;
this.xsiTypeMap = Collections.unmodifiableMap(xsiTypeMap); this.xsiTypeMap = Collections.unmodifiableMap(xsiTypeMap);
@@ -189,7 +203,9 @@ public class XMLParserConfiguration extends ParserConfiguration {
this.xsiTypeMap, this.xsiTypeMap,
this.forceList, this.forceList,
this.maxNestingDepth, this.maxNestingDepth,
this.closeEmptyTag this.closeEmptyTag,
this.keepNumberAsString,
this.keepBooleanAsString
); );
config.shouldTrimWhiteSpace = this.shouldTrimWhiteSpace; config.shouldTrimWhiteSpace = this.shouldTrimWhiteSpace;
return config; return config;
@@ -207,7 +223,43 @@ public class XMLParserConfiguration extends ParserConfiguration {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public XMLParserConfiguration withKeepStrings(final boolean newVal) { public XMLParserConfiguration withKeepStrings(final boolean newVal) {
return super.withKeepStrings(newVal); XMLParserConfiguration newConfig = this.clone();
newConfig.keepStrings = newVal;
newConfig.keepNumberAsString = newVal;
newConfig.keepBooleanAsString = newVal;
return newConfig;
}
/**
* When parsing the XML into JSON, specifies if numbers should be kept as strings (<code>1</code>), or if
* they should try to be guessed into JSON values (numeric, boolean, string)
*
* @param newVal
* new value to use for the <code>keepNumberAsString</code> configuration option.
*
* @return The existing configuration will not be modified. A new configuration is returned.
*/
public XMLParserConfiguration withKeepNumberAsString(final boolean newVal) {
XMLParserConfiguration newConfig = this.clone();
newConfig.keepNumberAsString = newVal;
newConfig.keepStrings = newConfig.keepBooleanAsString && newConfig.keepNumberAsString;
return newConfig;
}
/**
* When parsing the XML into JSON, specifies if booleans should be kept as strings (<code>true</code>), or if
* they should try to be guessed into JSON values (numeric, boolean, string)
*
* @param newVal
* new value to use for the <code>withKeepBooleanAsString</code> configuration option.
*
* @return The existing configuration will not be modified. A new configuration is returned.
*/
public XMLParserConfiguration withKeepBooleanAsString(final boolean newVal) {
XMLParserConfiguration newConfig = this.clone();
newConfig.keepBooleanAsString = newVal;
newConfig.keepStrings = newConfig.keepBooleanAsString && newConfig.keepNumberAsString;
return newConfig;
} }
/** /**
@@ -221,6 +273,26 @@ public class XMLParserConfiguration extends ParserConfiguration {
return this.cDataTagName; return this.cDataTagName;
} }
/**
* When parsing the XML into JSONML, specifies if numbers should be kept as strings (<code>true</code>), or if
* they should try to be guessed into JSON values (numeric, boolean, string).
*
* @return The <code>keepStrings</code> configuration value.
*/
public boolean isKeepNumberAsString() {
return this.keepNumberAsString;
}
/**
* When parsing the XML into JSONML, specifies if booleans should be kept as strings (<code>true</code>), or if
* they should try to be guessed into JSON values (numeric, boolean, string).
*
* @return The <code>keepStrings</code> configuration value.
*/
public boolean isKeepBooleanAsString() {
return this.keepBooleanAsString;
}
/** /**
* The name of the key in a JSON Object that indicates a CDATA section. Historically this has * The name of the key in a JSON Object that indicates a CDATA section. Historically this has
* been the value "content" but can be changed. Use <code>null</code> to indicate no CDATA * been the value "content" but can be changed. Use <code>null</code> to indicate no CDATA
+94 -12
View File
@@ -151,33 +151,115 @@ public class XMLTokener extends JSONTokener {
/** /**
* Unescape an XML entity encoding; * Unescape an XML entity encoding;
* @param e entity (only the actual entity value, not the preceding & or ending ; * @param e entity (only the actual entity value, not the preceding & or ending ;
* @return * @return the unescaped entity string
* @throws JSONException if the entity is malformed
*/ */
static String unescapeEntity(String e) { static String unescapeEntity(String e) throws JSONException {
// validate // validate
if (e == null || e.isEmpty()) { if (e == null || e.isEmpty()) {
return ""; return "";
} }
// if our entity is an encoded unicode point, parse it. // if our entity is an encoded unicode point, parse it.
if (e.charAt(0) == '#') { if (e.charAt(0) == '#') {
int cp; if (e.length() < 2) {
if (e.charAt(1) == 'x' || e.charAt(1) == 'X') { throw new JSONException("Invalid numeric character reference: &#;");
// hex encoded unicode
cp = Integer.parseInt(e.substring(2), 16);
} else {
// decimal encoded unicode
cp = Integer.parseInt(e.substring(1));
} }
return new String(new int[] {cp},0,1); int cp = (e.charAt(1) == 'x' || e.charAt(1) == 'X')
} ? parseHexEntity(e)
: parseDecimalEntity(e);
// Validate with isValidXmlCharacter, not with XML.mustEscape:
// mustEscape also escapes TAB/LF/CR for the serialization path
// (#1092), while the numeric references &#9;, &#10; and &#13; are
// valid XML and must keep being accepted here (see #1059).
if (!XML.isValidXmlCharacter(cp)) {
throw new JSONException("Invalid numeric character reference: &#" + e.substring(1) + ";");
}
return new String(new int[] {cp}, 0, 1);
}
Character knownEntity = entity.get(e); Character knownEntity = entity.get(e);
if(knownEntity==null) { if (knownEntity == null) {
// we don't know the entity so keep it encoded // we don't know the entity so keep it encoded
return '&' + e + ';'; return '&' + e + ';';
} }
return knownEntity.toString(); return knownEntity.toString();
} }
/**
* Parse a hexadecimal numeric character reference (e.g., "&#xABC;").
* @param e entity string starting with '#' (e.g., "#x1F4A9")
* @return the Unicode code point
* @throws JSONException if the format is invalid
*/
private static int parseHexEntity(String e) throws JSONException {
// hex encoded unicode - need at least one hex digit after #x
if (e.length() < 3) {
throw new JSONException("Invalid hex character reference: missing hex digits in &#" + e.substring(1) + ";");
}
String hex = e.substring(2);
if (!isValidHex(hex)) {
throw new JSONException("Invalid hex character reference: &#" + e.substring(1) + ";");
}
try {
return Integer.parseInt(hex, 16);
} catch (NumberFormatException nfe) {
throw new JSONException("Invalid hex character reference: &#" + e.substring(1) + ";", nfe);
}
}
/**
* Parse a decimal numeric character reference (e.g., "&#123;").
* @param e entity string starting with '#' (e.g., "#123")
* @return the Unicode code point
* @throws JSONException if the format is invalid
*/
private static int parseDecimalEntity(String e) throws JSONException {
String decimal = e.substring(1);
if (!isValidDecimal(decimal)) {
throw new JSONException("Invalid decimal character reference: &#" + decimal + ";");
}
try {
return Integer.parseInt(decimal);
} catch (NumberFormatException nfe) {
throw new JSONException("Invalid decimal character reference: &#" + decimal + ";", nfe);
}
}
/**
* Check if a string contains only valid hexadecimal digits.
* @param s the string to check
* @return true if s is non-empty and contains only hex digits (0-9, a-f, A-F)
*/
private static boolean isValidHex(String s) {
if (s == null || s.isEmpty()) {
return false;
}
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) {
return false;
}
}
return true;
}
/**
* Check if a string contains only valid decimal digits.
* @param s the string to check
* @return true if s is non-empty and contains only digits (0-9)
*/
private static boolean isValidDecimal(String s) {
if (s == null || s.isEmpty()) {
return false;
}
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
/** /**
* <pre>{@code * <pre>{@code
+27
View File
@@ -168,6 +168,33 @@ public class CDLTest {
} }
} }
/**
* Csv parsing skip last row if last field of this row is empty #943
*/
@Test
public void csvParsingCatchesLastRow(){
String data = "Field 1,Field 2,Field 3\n" +
"value11,value12,\n" +
"value21,value22,";
JSONArray jsonArray = CDL.toJSONArray(data);
JSONArray expectedJsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("Field 1", "value11");
jsonObject.put("Field 2", "value12");
jsonObject.put("Field 3", "");
expectedJsonArray.put(jsonObject);
jsonObject = new JSONObject();
jsonObject.put("Field 1", "value21");
jsonObject.put("Field 2", "value22");
jsonObject.put("Field 3", "");
expectedJsonArray.put(jsonObject);
Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray);
}
/** /**
* Assert that there is no error for a single escaped quote within a properly embedded quote. * Assert that there is no error for a single escaped quote within a properly embedded quote.
*/ */
@@ -0,0 +1,107 @@
package org.json.junit;
import org.json.HTTPTokener;
import org.json.JSONException;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Tests for JSON-Java HTTPTokener.java
*/
public class HTTPTokenerTest {
/**
* Test parsing a simple unquoted token.
*/
@Test
public void parseSimpleToken() {
HTTPTokener tokener = new HTTPTokener("Content-Type");
String token = tokener.nextToken();
assertEquals("Content-Type", token);
}
/**
* Test parsing multiple tokens separated by whitespace.
*/
@Test
public void parseMultipleTokens() {
HTTPTokener tokener = new HTTPTokener("Content-Type application/json");
String token1 = tokener.nextToken();
String token2 = tokener.nextToken();
assertEquals("Content-Type", token1);
assertEquals("application/json", token2);
}
/**
* Test parsing a double-quoted token.
*/
@Test
public void parseDoubleQuotedToken() {
HTTPTokener tokener = new HTTPTokener("\"application/json\"");
String token = tokener.nextToken();
assertEquals("application/json", token);
}
/**
* Test parsing a single-quoted token.
*/
@Test
public void parseSingleQuotedToken() {
HTTPTokener tokener = new HTTPTokener("'application/json'");
String token = tokener.nextToken();
assertEquals("application/json", token);
}
/**
* Test parsing a quoted token that includes spaces and semicolons.
*/
@Test
public void parseQuotedTokenWithSpaces() {
HTTPTokener tokener = new HTTPTokener("\"text/html; charset=UTF-8\"");
String token = tokener.nextToken();
assertEquals("text/html; charset=UTF-8", token);
}
/**
* Test that unterminated quoted strings throw a JSONException.
*/
@Test
public void throwExceptionOnUnterminatedString() {
HTTPTokener tokener = new HTTPTokener("\"incomplete");
JSONException exception = assertThrows(JSONException.class, tokener::nextToken);
assertTrue(exception.getMessage().contains("Unterminated string"));
}
/**
* Test behavior with empty input string.
*/
@Test
public void parseEmptyInput() {
HTTPTokener tokener = new HTTPTokener("");
String token = tokener.nextToken();
assertEquals("", token);
}
/**
* Test behavior with input consisting only of whitespace.
*/
@Test
public void parseWhitespaceOnly() {
HTTPTokener tokener = new HTTPTokener(" \t \n ");
String token = tokener.nextToken();
assertEquals("", token);
}
/**
* Test parsing tokens separated by multiple whitespace characters.
*/
@Test
public void parseTokensWithMultipleWhitespace() {
HTTPTokener tokener = new HTTPTokener("GET /index.html");
String method = tokener.nextToken();
String path = tokener.nextToken();
assertEquals("GET", method);
assertEquals("/index.html", path);
}
}
+110 -9
View File
@@ -8,6 +8,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@@ -227,6 +228,19 @@ public class JSONArrayTest {
Util.checkJSONArrayMaps(jaRaw); Util.checkJSONArrayMaps(jaRaw);
Util.checkJSONArrayMaps(jaInt); Util.checkJSONArrayMaps(jaInt);
} }
@Test
public void jsonArrayByListWithNestedNullValue() {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> sub = new HashMap<String, Object>();
sub.put("nullKey", null);
list.add(sub);
JSONParserConfiguration parserConfiguration = new JSONParserConfiguration().withUseNativeNulls(true);
JSONArray jsonArray = new JSONArray(list, parserConfiguration);
JSONObject subObject = jsonArray.getJSONObject(0);
assertTrue(subObject.has("nullKey"));
assertEquals(JSONObject.NULL, subObject.get("nullKey"));
}
/** /**
* Tests consecutive calls to putAll with array and collection. * Tests consecutive calls to putAll with array and collection.
@@ -476,13 +490,18 @@ public class JSONArrayTest {
*/ */
@Test @Test
public void unquotedText() { public void unquotedText() {
String str = "[value1, something!, (parens), [email protected], 23, 23+45]";
List<Object> expected = Arrays.asList("value1", "something!", "(parens)", "[email protected]", 23, "23+45");
// Test should fail if default strictMode is true, pass if false
JSONParserConfiguration jsonParserConfiguration = new JSONParserConfiguration(); JSONParserConfiguration jsonParserConfiguration = new JSONParserConfiguration();
if (jsonParserConfiguration.isStrictMode()) { if (jsonParserConfiguration.isStrictMode()) {
System.out.println("Skipping JSONArrayTest unquotedText() when strictMode default is true"); try {
} else {
String str = "[value1, something!, (parens), [email protected], 23, 23+45]";
JSONArray jsonArray = new JSONArray(str); JSONArray jsonArray = new JSONArray(str);
List<Object> expected = Arrays.asList("value1", "something!", "(parens)", "[email protected]", 23, "23+45"); assertEquals("Expected to throw exception due to invalid string", true, false);
} catch (JSONException e) { }
} else {
JSONArray jsonArray = new JSONArray(str);
assertEquals(expected, jsonArray.toList()); assertEquals(expected, jsonArray.toList());
} }
} }
@@ -1483,19 +1502,23 @@ public class JSONArrayTest {
} }
@Test @Test
public void testRecursiveDepthArrayFor1000Levels() { /**
* This test was originally for 1000 levels, which passes in test builds, but fails on my laptop.
* The current value of 900 seems to work.
*/
public void testRecursiveDepthArrayFor900Levels() {
try { try {
ArrayList<Object> array = buildNestedArray(1000); ArrayList<Object> array = buildNestedArray(900);
JSONParserConfiguration parserConfiguration = new JSONParserConfiguration().withMaxNestingDepth(1000); JSONParserConfiguration parserConfiguration = new JSONParserConfiguration().withMaxNestingDepth(900);
new JSONArray(array, parserConfiguration); new JSONArray(array, parserConfiguration);
} catch (StackOverflowError e) { } catch (StackOverflowError e) {
String javaVersion = System.getProperty("java.version"); String javaVersion = System.getProperty("java.version");
if (javaVersion.startsWith("11.")) { if (javaVersion.startsWith("11.")) {
System.out.println( System.out.println(
"testRecursiveDepthArrayFor1000Levels() allowing intermittent stackoverflow, Java Version: " "testRecursiveDepthArrayFor900Levels() allowing intermittent stackoverflow, Java Version: "
+ javaVersion); + javaVersion);
} else { } else {
String errorStr = "testRecursiveDepthArrayFor1000Levels() unexpected stackoverflow, Java Version: " String errorStr = "testRecursiveDepthArrayFor900Levels() unexpected stackoverflow, Java Version: "
+ javaVersion; + javaVersion;
System.out.println(errorStr); System.out.println(errorStr);
throw new RuntimeException(errorStr); throw new RuntimeException(errorStr);
@@ -1509,6 +1532,14 @@ public class JSONArrayTest {
new JSONArray(array); new JSONArray(array);
} }
@Test
public void testStrictModeJSONTokener_expectException(){
JSONParserConfiguration jsonParserConfiguration = new JSONParserConfiguration().withStrictMode();
JSONTokener tokener = new JSONTokener("[\"value\"]invalidCharacters", jsonParserConfiguration);
assertThrows(JSONException.class, () -> { new JSONArray(tokener); });
}
public static ArrayList<Object> buildNestedArray(int maxDepth) { public static ArrayList<Object> buildNestedArray(int maxDepth) {
if (maxDepth <= 0) { if (maxDepth <= 0) {
return new ArrayList<>(); return new ArrayList<>();
@@ -1517,4 +1548,74 @@ public class JSONArrayTest {
nestedArray.add(buildNestedArray(maxDepth - 1)); nestedArray.add(buildNestedArray(maxDepth - 1));
return nestedArray; return nestedArray;
} }
@Test
public void TestLenientCommas() {
String str = "[1,,3]";
// Test should fail if default strictMode is true, pass with an extra null entry if false
JSONParserConfiguration jsonParserConfiguration = new JSONParserConfiguration();
if (jsonParserConfiguration.isStrictMode()) {
try {
new JSONArray(str);
fail("Expected to throw exception due to invalid string");
} catch (JSONException e) { /* no action is needed here */ }
} else {
JSONArray jsonArray = new JSONArray(str);
assertEquals("JSONArray in non-strictMode should contain a null entry",
"[1,null,3]", jsonArray.toString());
}
}
@Test
public void strictModeShouldCheckTrailingCharactersAfterNextAndBack() {
JSONParserConfiguration strict =
new JSONParserConfiguration().withStrictMode();
JSONTokener tok = new JSONTokener("[]xxx");
tok.next();
tok.back();
JSONException exception = assertThrows(
JSONException.class,
() -> new JSONArray(tok, strict));
assertTrue(exception.getMessage().contains(
"Unparsed characters found at end of input text"));
}
@Test
public void strictModeShouldCheckTrailingCharactersAfterConsumedWhitespace() {
JSONParserConfiguration strict =
new JSONParserConfiguration().withStrictMode();
JSONTokener tok = new JSONTokener(" []xxx");
tok.next();
tok.next();
tok.back();
JSONException exception = assertThrows(
JSONException.class,
() -> new JSONArray(tok, strict));
assertTrue(exception.getMessage().contains(
"Unparsed characters found at end of input text"));
}
@Test
public void strictModeShouldCheckTrailingCharactersAfterNextCleanAndBack() {
JSONParserConfiguration strict =
new JSONParserConfiguration().withStrictMode();
JSONTokener tok = new JSONTokener(" []xxx");
tok.nextClean();
tok.back();
JSONException exception = assertThrows(
JSONException.class,
() -> new JSONArray(tok, strict));
assertTrue(exception.getMessage().contains(
"Unparsed characters found at end of input text"));
}
} }
@@ -724,6 +724,98 @@ public class JSONMLTest {
assertNotEquals(revertedXml, originalXml); assertNotEquals(revertedXml, originalXml);
} }
/**
* Entity-looking text is decoded once, including when strings are kept.
*/
@Test
public void shouldDecodeEntitiesOnceWhenKeepingStringsInJSONArray() {
final String[][] cases = {
{"&amp;lt;", "&lt;"},
{"&amp;amp;", "&amp;"},
{"&amp;#65;", "&#65;"},
{"&#38;lt;", "&lt;"},
{"&lt;&gt;&amp;&quot;&apos;&#65;&#x42;", "<>&\"'AB"}
};
for (String[] testCase : cases) {
final String xml = "<p title=\"" + testCase[0] + "\">" + testCase[0] + "</p>";
final JSONArray json = JSONML.toJSONArray(xml, true);
assertEquals(xml, testCase[1], json.getJSONObject(1).get("title"));
assertEquals(xml, testCase[1], json.get(2));
assertEquals(xml, testCase[1], JSONML.toJSONArray(xml, false).get(2));
assertTrue(xml, json.similar(JSONML.toJSONArray(new XMLTokener(JSONML.toString(json)),
JSONMLParserConfiguration.KEEP_STRINGS)));
}
}
/**
* Object form preserves the same decoded attribute and text values.
*/
@Test
public void shouldDecodeEntitiesOnceWhenKeepingStringsInJSONObject() {
final String xml = "<p title=\"&amp;lt;\">&amp;lt;</p>";
final JSONObject json = JSONML.toJSONObject(xml,
JSONMLParserConfiguration.ORIGINAL.withKeepStrings(true));
assertEquals("&lt;", json.get("title"));
assertEquals("&lt;", json.getJSONArray("childNodes").get(0));
assertEquals("&lt;", JSONML.toJSONObject(xml).getJSONArray("childNodes").get(0));
assertTrue(json.similar(JSONML.toJSONObject(new XMLTokener(JSONML.toString(json)), true)));
}
/**
* Keeping strings disables type conversion without disabling entity decoding.
*/
@Test
public void shouldPreserveValueTypesWhenKeepingStrings() {
final String[] values = {"42", "true", "false", "null"};
final String[] content = {"&#52;&#50;", "&#116;rue", "false", "null"};
final Object[] typedValues = {Integer.valueOf(42), Boolean.TRUE, Boolean.FALSE, JSONObject.NULL};
for (int i = 0; i < values.length; i++) {
final String xml = "<p value=\"" + values[i] + "\">" + content[i] + "</p>";
final JSONArray array = JSONML.toJSONArray(new XMLTokener(xml), true);
final JSONObject object = JSONML.toJSONObject(xml, true);
assertEquals(values[i], array.getJSONObject(1).get("value"));
assertEquals(values[i], array.get(2));
assertEquals(values[i], object.get("value"));
assertEquals(values[i], object.getJSONArray("childNodes").get(0));
final JSONArray typedArray = JSONML.toJSONArray(xml);
final JSONObject typedObject = JSONML.toJSONObject(xml);
assertEquals(typedValues[i], typedArray.getJSONObject(1).get("value"));
assertEquals(typedValues[i], typedArray.get(2));
assertEquals(typedValues[i], typedObject.get("value"));
assertEquals(typedValues[i], typedObject.getJSONArray("childNodes").get(0));
}
}
/**
* CDATA entity syntax remains literal content.
*/
@Test
public void shouldPreserveCdataWhenKeepingStrings() {
final String content = "&lt; &#65; &amp; 42 true null";
final String xml = "<p><![CDATA[" + content + "]]></p>";
assertEquals(content, JSONML.toJSONArray(xml, true).get(1));
assertEquals(content, JSONML.toJSONObject(xml, true).getJSONArray("childNodes").get(0));
}
/**
* Escaped invalid character references are text, while raw references remain invalid.
*/
@Test
public void shouldPreserveEscapedInvalidCharacterReferences() {
final String[] references = {"#0", "#x110000"};
for (String reference : references) {
final String expected = "&" + reference + ";";
final String xml = "<p>&amp;" + reference + ";</p>";
assertEquals(expected, JSONML.toJSONArray(xml, true).get(1));
assertEquals(expected, JSONML.toJSONObject(xml, true).getJSONArray("childNodes").get(0));
assertEquals(expected, JSONML.toJSONArray(xml).get(1));
assertEquals(expected, JSONML.toJSONObject(xml).getJSONArray("childNodes").get(0));
final String invalidXml = "<p>" + expected + "</p>";
assertThrows(JSONException.class, () -> JSONML.toJSONArray(invalidXml, true));
assertThrows(JSONException.class, () -> JSONML.toJSONObject(invalidXml, true));
}
}
/** /**
* JSON string cannot be reverted to original xml when type guessing is used. * JSON string cannot be reverted to original xml when type guessing is used.
* When we force all the values as string, the original text comes back. * When we force all the values as string, the original text comes back.
@@ -986,4 +1078,127 @@ public class JSONMLTest {
} }
} }
/**
* Tests that malformed XML causing type mismatch throws JSONException.
* Previously threw ClassCastException when parse() returned String instead of JSONArray.
* Related to issue #1034
*/
@Test(expected = JSONException.class)
public void testMalformedXMLThrowsJSONExceptionNotClassCast() {
// This malformed XML causes parse() to return wrong type
byte[] data = {0x3c, 0x0a, 0x2f, (byte)0xff, (byte)0xff, (byte)0xff,
(byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff,
(byte)0xff, 0x3e, 0x42};
String xmlStr = new String(data);
JSONML.toJSONArray(xmlStr);
}
/**
* Tests that type mismatch in toJSONObject throws JSONException.
* Validates safe type casting in toJSONObject methods.
*/
@Test
public void testToJSONObjectTypeMismatch() {
// Create XML that would cause parse() to return wrong type
String xmlStr = "<\n/\u00ff\u00ff\u00ff\u00ff\u00ff\u00ff\u00ff\u00ff>B";
try {
JSONML.toJSONObject(xmlStr);
fail("Expected JSONException for type mismatch");
} catch (ClassCastException e) {
fail("Should throw JSONException, not ClassCastException");
} catch (JSONException e) {
// Expected - verify it's about type mismatch
assertTrue("Exception message should mention type error",
e.getMessage().contains("Expected") || e.getMessage().contains("got"));
}
}
/**
* Tests that valid XML still works correctly after the fix.
* Ensures the type checking doesn't break normal operation.
*/
@Test
public void testValidXMLStillWorks() {
String xmlStr = "<root><item>value</item></root>";
try {
JSONArray jsonArray = JSONML.toJSONArray(xmlStr);
assertNotNull("JSONArray should not be null", jsonArray);
assertEquals("root", jsonArray.getString(0));
} catch (Exception e) {
fail("Valid XML should not throw exception: " + e.getMessage());
}
}
/**
* Tests that valid XML to JSONObject still works correctly.
*/
@Test
public void testValidXMLToJSONObjectStillWorks() {
String xmlStr = "<root attr=\"value\"><item>content</item></root>";
try {
JSONObject jsonObject = JSONML.toJSONObject(xmlStr);
assertNotNull("JSONObject should not be null", jsonObject);
assertEquals("root", jsonObject.getString("tagName"));
} catch (Exception e) {
fail("Valid XML should not throw exception: " + e.getMessage());
}
}
/**
* Tests that the childNodes attribute is reserved in object-form parsing.
*/
@Test
public void testToJSONObjectRejectsReservedChildNodesAttribute() {
String xmlStr = "<p childNodes=\"metadata\">text</p>";
for (boolean keepStrings : new boolean[] {false, true}) {
JSONException exception = assertThrows(JSONException.class,
() -> JSONML.toJSONObject(xmlStr, keepStrings));
assertTrue(exception.getMessage().startsWith("Reserved attribute."));
}
}
/**
* Tests that the ordinary childNode attribute is preserved in object-form parsing.
*/
@Test
public void testToJSONObjectPreservesChildNodeAttribute() {
String xmlStr = "<p childNode=\"metadata\">text</p>";
for (boolean keepStrings : new boolean[] {false, true}) {
JSONObject jsonObject = JSONML.toJSONObject(xmlStr, keepStrings);
assertEquals("p", jsonObject.getString("tagName"));
assertEquals("metadata", jsonObject.getString("childNode"));
assertEquals("text", jsonObject.getJSONArray("childNodes").getString(0));
}
}
/**
* Tests that the tagName attribute remains reserved in object-form parsing.
*/
@Test
public void testToJSONObjectRejectsReservedTagNameAttribute() {
String xmlStr = "<p tagName=\"metadata\">text</p>";
for (boolean keepStrings : new boolean[] {false, true}) {
JSONException exception = assertThrows(JSONException.class,
() -> JSONML.toJSONObject(xmlStr, keepStrings));
assertTrue(exception.getMessage().startsWith("Reserved attribute."));
}
}
/**
* Tests that childNode and childNodes attributes are preserved in array-form parsing.
*/
@Test
public void testToJSONArrayPreservesChildNodeAttributes() {
String xmlStr = "<p childNode=\"singular\" childNodes=\"plural\">text</p>";
for (boolean keepStrings : new boolean[] {false, true}) {
JSONArray jsonArray = JSONML.toJSONArray(xmlStr, keepStrings);
assertEquals(3, jsonArray.length());
assertEquals("p", jsonArray.getString(0));
JSONObject attributes = jsonArray.getJSONObject(1);
assertEquals("singular", attributes.getString("childNode"));
assertEquals("plural", attributes.getString("childNodes"));
assertEquals("text", jsonArray.getString(2));
}
}
} }
@@ -36,25 +36,31 @@ public class JSONObjectLocaleTest {
MyLocaleBean myLocaleBean = new MyLocaleBean(); MyLocaleBean myLocaleBean = new MyLocaleBean();
/** // save and restore the current default locale, to avoid any side effects on other executions in the same JVM
* This is just the control case which happens when the locale.ROOT Locale defaultLocale = Locale.getDefault();
* lowercasing behavior is the same as the current locale. try {
*/ /**
Locale.setDefault(new Locale("en")); * This is just the control case which happens when the locale.ROOT
JSONObject jsonen = new JSONObject(myLocaleBean); * lowercasing behavior is the same as the current locale.
assertEquals("expected size 2, found: " +jsonen.length(), 2, jsonen.length()); */
assertEquals("expected jsonen[i] == beanI", "beanI", jsonen.getString("i")); Locale.setDefault(new Locale("en"));
assertEquals("expected jsonen[id] == beanId", "beanId", jsonen.getString("id")); JSONObject jsonen = new JSONObject(myLocaleBean);
assertEquals("expected size 2, found: " +jsonen.length(), 2, jsonen.length());
assertEquals("expected jsonen[i] == beanI", "beanI", jsonen.getString("i"));
assertEquals("expected jsonen[id] == beanId", "beanId", jsonen.getString("id"));
/** /**
* Without the JSON-Java change, these keys would be stored internally as * Without the JSON-Java change, these keys would be stored internally as
* starting with the letter, 'ı' (dotless i), since the lowercasing of * starting with the letter, 'ı' (dotless i), since the lowercasing of
* the getI and getId keys would be specific to the Turkish locale. * the getI and getId keys would be specific to the Turkish locale.
*/ */
Locale.setDefault(new Locale("tr")); Locale.setDefault(new Locale("tr"));
JSONObject jsontr = new JSONObject(myLocaleBean); JSONObject jsontr = new JSONObject(myLocaleBean);
assertEquals("expected size 2, found: " +jsontr.length(), 2, jsontr.length()); assertEquals("expected size 2, found: " +jsontr.length(), 2, jsontr.length());
assertEquals("expected jsontr[i] == beanI", "beanI", jsontr.getString("i")); assertEquals("expected jsontr[i] == beanI", "beanI", jsontr.getString("i"));
assertEquals("expected jsontr[id] == beanId", "beanId", jsontr.getString("id")); assertEquals("expected jsontr[id] == beanId", "beanId", jsontr.getString("id"));
} finally {
Locale.setDefault(defaultLocale);
}
} }
} }
@@ -0,0 +1,179 @@
package org.json.junit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.StringReader;
import org.json.JSONObject;
import org.json.junit.data.GenericBeanInt;
import org.json.junit.data.MyEnum;
import org.json.junit.data.MyNumber;
import org.json.junit.data.PersonRecord;
import org.junit.Ignore;
import org.junit.Test;
/**
* Tests for JSONObject support of Java record types.
*
* NOTE: These tests are currently ignored because PersonRecord is not an actual Java record.
* The implementation now correctly detects actual Java records using reflection (Class.isRecord()).
* These tests will need to be enabled and run with Java 17+ where PersonRecord can be converted
* to an actual record type.
*
* This ensures backward compatibility - regular classes with lowercase method names will not
* be treated as records unless they are actual Java record types.
*/
public class JSONObjectRecordTest {
/**
* Tests that JSONObject can be created from a record-style class.
* Record-style classes use accessor methods like name() instead of getName().
*
* NOTE: Ignored until PersonRecord is converted to an actual Java record (requires Java 17+)
*/
@Test
@Ignore("Requires actual Java record type - PersonRecord needs to be a real record (Java 17+)")
public void jsonObjectByRecord() {
PersonRecord person = new PersonRecord("John Doe", 30, true);
JSONObject jsonObject = new JSONObject(person);
assertEquals("Expected 3 keys in the JSONObject", 3, jsonObject.length());
assertEquals("John Doe", jsonObject.get("name"));
assertEquals(30, jsonObject.get("age"));
assertEquals(true, jsonObject.get("active"));
}
/**
* Test that Object methods (toString, hashCode, equals, etc.) are not included
*
* NOTE: Ignored until PersonRecord is converted to an actual Java record (requires Java 17+)
*/
@Test
@Ignore("Requires actual Java record type - PersonRecord needs to be a real record (Java 17+)")
public void recordStyleClassShouldNotIncludeObjectMethods() {
PersonRecord person = new PersonRecord("Jane Doe", 25, false);
JSONObject jsonObject = new JSONObject(person);
// Should NOT include Object methods
assertFalse("Should not include toString", jsonObject.has("toString"));
assertFalse("Should not include hashCode", jsonObject.has("hashCode"));
assertFalse("Should not include equals", jsonObject.has("equals"));
assertFalse("Should not include clone", jsonObject.has("clone"));
assertFalse("Should not include wait", jsonObject.has("wait"));
assertFalse("Should not include notify", jsonObject.has("notify"));
assertFalse("Should not include notifyAll", jsonObject.has("notifyAll"));
// Should only have the 3 record fields
assertEquals("Should only have 3 fields", 3, jsonObject.length());
}
/**
* Test that enum methods are not included when processing an enum
*/
@Test
public void enumsShouldNotIncludeEnumMethods() {
MyEnum myEnum = MyEnum.VAL1;
JSONObject jsonObject = new JSONObject(myEnum);
// Should NOT include enum-specific methods like name(), ordinal(), values(), valueOf()
assertFalse("Should not include name method", jsonObject.has("name"));
assertFalse("Should not include ordinal method", jsonObject.has("ordinal"));
assertFalse("Should not include declaringClass", jsonObject.has("declaringClass"));
// Enums should still work with traditional getters if they have any
// But should not pick up the built-in enum methods
}
/**
* Test that Number subclass methods are not included
*/
@Test
public void numberSubclassesShouldNotIncludeNumberMethods() {
MyNumber myNumber = new MyNumber();
JSONObject jsonObject = new JSONObject(myNumber);
// Should NOT include Number methods like intValue(), longValue(), etc.
assertFalse("Should not include intValue", jsonObject.has("intValue"));
assertFalse("Should not include longValue", jsonObject.has("longValue"));
assertFalse("Should not include doubleValue", jsonObject.has("doubleValue"));
assertFalse("Should not include floatValue", jsonObject.has("floatValue"));
// Should include the actual getter
assertTrue("Should include number", jsonObject.has("number"));
assertEquals("Should have 1 field", 1, jsonObject.length());
}
/**
* Test that generic bean with get() and is() methods works correctly
*/
@Test
public void genericBeanWithGetAndIsMethodsShouldNotBeIncluded() {
GenericBeanInt bean = new GenericBeanInt(42);
JSONObject jsonObject = new JSONObject(bean);
// Should NOT include standalone get() or is() methods
assertFalse("Should not include standalone 'get' method", jsonObject.has("get"));
assertFalse("Should not include standalone 'is' method", jsonObject.has("is"));
// Should include the actual getters
assertTrue("Should include genericValue field", jsonObject.has("genericValue"));
assertTrue("Should include a field", jsonObject.has("a"));
}
/**
* Test that java.* classes don't have their methods picked up
*/
@Test
public void javaLibraryClassesShouldNotIncludeTheirMethods() {
StringReader reader = new StringReader("test");
JSONObject jsonObject = new JSONObject(reader);
// Should NOT include java.io.Reader methods like read(), reset(), etc.
assertFalse("Should not include read method", jsonObject.has("read"));
assertFalse("Should not include reset method", jsonObject.has("reset"));
assertFalse("Should not include ready method", jsonObject.has("ready"));
assertFalse("Should not include skip method", jsonObject.has("skip"));
// Reader should produce empty JSONObject (no valid properties)
assertEquals("Reader should produce empty JSON", 0, jsonObject.length());
}
/**
* Test mixed case - object with both traditional getters and record-style accessors
*
* NOTE: Ignored until PersonRecord is converted to an actual Java record (requires Java 17+)
*/
@Test
@Ignore("Requires actual Java record type - PersonRecord needs to be a real record (Java 17+)")
public void mixedGettersAndRecordStyleAccessors() {
// PersonRecord has record-style accessors: name(), age(), active()
// These should all be included
PersonRecord person = new PersonRecord("Mixed Test", 40, true);
JSONObject jsonObject = new JSONObject(person);
assertEquals("Should have all 3 record-style fields", 3, jsonObject.length());
assertTrue("Should include name", jsonObject.has("name"));
assertTrue("Should include age", jsonObject.has("age"));
assertTrue("Should include active", jsonObject.has("active"));
}
/**
* Test that methods starting with uppercase are not included (not valid record accessors)
*
* NOTE: Ignored until PersonRecord is converted to an actual Java record (requires Java 17+)
*/
@Test
@Ignore("Requires actual Java record type - PersonRecord needs to be a real record (Java 17+)")
public void methodsStartingWithUppercaseShouldNotBeIncluded() {
PersonRecord person = new PersonRecord("Test", 50, false);
JSONObject jsonObject = new JSONObject(person);
// Record-style accessors must start with lowercase
// Methods like Name(), Age() (uppercase) should not be picked up
// Our PersonRecord only has lowercase accessors, which is correct
assertEquals("Should only have lowercase accessors", 3, jsonObject.length());
}
}
File diff suppressed because one or more lines are too long
@@ -4,6 +4,7 @@ import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.json.JSONParserConfiguration; import org.json.JSONParserConfiguration;
import org.json.JSONTokener;
import org.junit.Test; import org.junit.Test;
import java.io.IOException; import java.io.IOException;
@@ -14,7 +15,13 @@ import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
import static org.junit.Assert.*; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
public class JSONParserConfigurationTest { public class JSONParserConfigurationTest {
private static final String TEST_SOURCE = "{\"key\": \"value1\", \"key\": \"value2\"}"; private static final String TEST_SOURCE = "{\"key\": \"value1\", \"key\": \"value2\"}";
@@ -32,6 +39,118 @@ public class JSONParserConfigurationTest {
assertEquals("duplicate key should be overwritten", "value2", jsonObject.getString("key")); assertEquals("duplicate key should be overwritten", "value2", jsonObject.getString("key"));
} }
@Test
public void objectConstructorAppliesExplicitStrictModeToValues() {
JSONParserConfiguration configuration = new JSONParserConfiguration().withStrictMode();
JSONParserConfiguration lenient = new JSONParserConfiguration().withStrictMode(false);
for (String source : Arrays.asList(
"[]",
"{",
"{} trailing",
"{\"value\":'text'}",
"{\"value\":[1,]}",
"{\"value\":{\"nested\":1,}}")) {
JSONTokener tokener = new JSONTokener(source, lenient);
assertThrows(JSONException.class, () -> new JSONObject(tokener, configuration));
assertSame(lenient, tokener.getJsonParserConfiguration());
}
}
@Test
public void arrayConstructorAppliesExplicitStrictModeToValues() {
JSONParserConfiguration configuration = new JSONParserConfiguration().withStrictMode();
JSONParserConfiguration lenient = new JSONParserConfiguration().withStrictMode(false);
for (String source : Arrays.asList(
"{}",
"[",
"[] trailing",
"['text']",
"[[1,]]",
"[{\"nested\":1,}]")) {
JSONTokener tokener = new JSONTokener(source, lenient);
assertThrows(JSONException.class, () -> new JSONArray(tokener, configuration));
assertSame(lenient, tokener.getJsonParserConfiguration());
}
}
@Test
public void explicitConfigurationOverridesTokenerStrictMode() {
JSONParserConfiguration strict = new JSONParserConfiguration().withStrictMode();
JSONParserConfiguration lenient = new JSONParserConfiguration().withStrictMode(false);
JSONTokener objectTokener = new JSONTokener("{\"value\":[{'nested':'text',}], 'other':'text'} 'next'", strict);
JSONTokener arrayTokener = new JSONTokener("[{\"value\":['text',]},'text'] 'next'", strict);
JSONObject object = new JSONObject(objectTokener, lenient);
JSONArray array = new JSONArray(arrayTokener, lenient);
assertEquals("text", object.getJSONArray("value").getJSONObject(0).getString("nested"));
assertEquals("text", array.getJSONObject(0).getJSONArray("value").getString(0));
assertEquals("text", object.getString("other"));
assertEquals("text", array.getString(1));
assertSame(strict, objectTokener.getJsonParserConfiguration());
assertSame(strict, arrayTokener.getJsonParserConfiguration());
assertThrows(JSONException.class, () -> objectTokener.nextValue());
assertThrows(JSONException.class, () -> arrayTokener.nextValue());
}
@Test
public void objectConstructorRestoresTokenerConfiguration() {
JSONParserConfiguration original = new JSONParserConfiguration().withStrictMode(false);
JSONParserConfiguration strict = new JSONParserConfiguration().withStrictMode();
for (String source : Arrays.asList("{}", "{\"value\":[{\"nested\":\"text\"}],\"other\":true}")) {
JSONTokener tokener = new JSONTokener(source, original);
new JSONObject(tokener, strict);
assertSame(original, tokener.getJsonParserConfiguration());
}
}
@Test
public void arrayConstructorRestoresTokenerConfiguration() {
JSONParserConfiguration original = new JSONParserConfiguration().withStrictMode(false);
JSONParserConfiguration strict = new JSONParserConfiguration().withStrictMode();
for (String source : Arrays.asList("[]", "[{\"value\":[\"text\"]},true]")) {
JSONTokener tokener = new JSONTokener(source, original);
new JSONArray(tokener, strict);
assertSame(original, tokener.getJsonParserConfiguration());
}
}
@Test
public void explicitConfigurationAppliesToNestedDuplicateKeys() {
JSONParserConfiguration configuration = new JSONParserConfiguration().withOverwriteDuplicateKey(true);
JSONObject object = new JSONObject(new JSONTokener("{\"value\":[{\"key\":1,\"key\":2}]}"), configuration);
JSONArray array = new JSONArray(new JSONTokener("[{\"value\":{\"key\":1,\"key\":2}}]"), configuration);
assertEquals(2, object.getJSONArray("value").getJSONObject(0).getInt("key"));
assertEquals(2, array.getJSONObject(0).getJSONObject("value").getInt("key"));
}
@Test
public void strictModeIsCloned(){
JSONParserConfiguration jsonParserConfiguration = new JSONParserConfiguration()
.withStrictMode(true)
.withMaxNestingDepth(12);
assertTrue(jsonParserConfiguration.isStrictMode());
}
@Test
public void maxNestingDepthIsCloned(){
JSONParserConfiguration jsonParserConfiguration = new JSONParserConfiguration()
.<JSONParserConfiguration>withKeepStrings(true)
.withStrictMode(true);
assertTrue(jsonParserConfiguration.isKeepStrings());
}
@Test
public void useNativeNullsIsCloned() {
JSONParserConfiguration jsonParserConfiguration = new JSONParserConfiguration()
.withUseNativeNulls(true)
.withStrictMode(true);
assertTrue(jsonParserConfiguration.isUseNativeNulls());
}
@Test @Test
public void verifyDuplicateKeyThenMaxDepth() { public void verifyDuplicateKeyThenMaxDepth() {
JSONParserConfiguration jsonParserConfiguration = new JSONParserConfiguration() JSONParserConfiguration jsonParserConfiguration = new JSONParserConfiguration()
@@ -490,6 +609,40 @@ public class JSONParserConfigurationTest {
je.getMessage()); je.getMessage());
} }
@Test
public void givenInvalidInputObject_testStrictModeTrue_JSONObjectUsingJSONTokener_shouldThrowJSONException() {
JSONException exception = assertThrows(JSONException.class, () -> {
new JSONObject(new JSONTokener("{\"key\":\"value\"} invalid trailing text"), new JSONParserConfiguration().withStrictMode(true));
});
assertEquals("Strict mode error: Unparsed characters found at end of input text at 17 [character 18 line 1]", exception.getMessage());
}
@Test
public void givenInvalidInputObject_testStrictModeTrue_JSONObjectUsingString_shouldThrowJSONException() {
JSONException exception = assertThrows(JSONException.class, () -> {
new JSONObject("{\"key\":\"value\"} invalid trailing text", new JSONParserConfiguration().withStrictMode(true));
});
assertEquals("Strict mode error: Unparsed characters found at end of input text at 17 [character 18 line 1]", exception.getMessage());
}
@Test
public void givenInvalidInputObject_testStrictModeTrue_JSONArrayUsingJSONTokener_shouldThrowJSONException() {
JSONException exception = assertThrows(JSONException.class, () -> {
new JSONArray(new JSONTokener("[\"value\"] invalid trailing text"), new JSONParserConfiguration().withStrictMode(true));
});
assertEquals("Strict mode error: Unparsed characters found at end of input text at 11 [character 12 line 1]", exception.getMessage());
}
@Test
public void givenInvalidInputObject_testStrictModeTrue_JSONArrayUsingString_shouldThrowJSONException() {
JSONException exception = assertThrows(JSONException.class, () -> {
new JSONArray("[\"value\"] invalid trailing text", new JSONParserConfiguration().withStrictMode(true));
});
assertEquals("Strict mode error: Unparsed characters found at end of input text at 11 [character 12 line 1]", exception.getMessage());
}
/** /**
* This method contains short but focused use-case samples and is exclusively used to test strictMode unit tests in * This method contains short but focused use-case samples and is exclusively used to test strictMode unit tests in
* this class. * this class.
@@ -557,4 +710,140 @@ public class JSONParserConfigurationTest {
); );
} }
private static final String SHARED_KEYS_SOURCE = "{\"rows\": ["
+ "{\"name\": \"a\", \"count\": 1, \"big\": 12345678901, \"ratio\": 1.5, \"flag\": true, \"missing\": null,"
+ " \"nested\": {\"name\": \"inner\", \"list\": [1, \"name\", null]}},"
+ "{\"name\": \"name\", \"count\": 2, \"nested\": {\"name\": \"inner2\", \"list\": []}},"
+ "{\"name\": \"third\", \"count\": -3}"
+ "]}";
@Test
public void testMaxSharedKeysConfig() {
JSONParserConfiguration config = new JSONParserConfiguration();
assertEquals(JSONParserConfiguration.DEFAULT_MAXIMUM_SHARED_KEYS, config.getMaxSharedKeys());
assertEquals(1000, config.getMaxSharedKeys());
assertEquals(0, config.withMaxSharedKeys(0).getMaxSharedKeys());
assertEquals(JSONParserConfiguration.UNLIMITED_SHARED_KEYS, config.withMaxSharedKeys(-1).getMaxSharedKeys());
assertEquals(JSONParserConfiguration.UNLIMITED_SHARED_KEYS, config.withMaxSharedKeys(-5).getMaxSharedKeys());
JSONParserConfiguration chained = config.withMaxSharedKeys(7).withOverwriteDuplicateKey(true).withStrictMode(false);
assertEquals(7, chained.getMaxSharedKeys());
assertTrue(chained.isOverwriteDuplicateKey());
assertEquals(1000, config.getMaxSharedKeys());
}
@Test
public void testSharedKeysByDefault() {
JSONArray rows = new JSONObject(SHARED_KEYS_SOURCE).getJSONArray("rows");
String nameKey = key(rows.getJSONObject(0), "name");
for (int i = 1; i < rows.length(); i++) {
assertSame(nameKey, key(rows.getJSONObject(i), "name"));
}
assertSame(nameKey, key(rows.getJSONObject(0).getJSONObject("nested"), "name"));
assertSame(key(rows.getJSONObject(0), "count"), key(rows.getJSONObject(2), "count"));
assertSame(key(rows.getJSONObject(0).getJSONObject("nested"), "list"),
key(rows.getJSONObject(1).getJSONObject("nested"), "list"));
// string values equal to a key are not shared
assertNotSame(nameKey, rows.getJSONObject(1).get("name"));
assertNotSame(nameKey, rows.getJSONObject(0).getJSONObject("nested").getJSONArray("list").get(1));
}
@Test
public void testSharedKeysDisabled() {
JSONArray rows = new JSONObject(SHARED_KEYS_SOURCE, new JSONParserConfiguration().withMaxSharedKeys(0))
.getJSONArray("rows");
assertNotSame(key(rows.getJSONObject(0), "name"), key(rows.getJSONObject(1), "name"));
assertNotSame(key(rows.getJSONObject(0), "count"), key(rows.getJSONObject(1), "count"));
}
@Test
public void testSharedKeysLimit() {
JSONArray rows = new JSONArray("[{\"a\": 1, \"b\": 2, \"c\": 3}, {\"a\": 4, \"b\": 5, \"c\": 6}]",
new JSONParserConfiguration().withMaxSharedKeys(2));
assertSame(key(rows.getJSONObject(0), "a"), key(rows.getJSONObject(1), "a"));
assertSame(key(rows.getJSONObject(0), "b"), key(rows.getJSONObject(1), "b"));
assertNotSame(key(rows.getJSONObject(0), "c"), key(rows.getJSONObject(1), "c"));
}
@Test
public void testSharedKeysUnlimited() {
int keyCount = JSONParserConfiguration.DEFAULT_MAXIMUM_SHARED_KEYS + 500;
StringBuilder row = new StringBuilder("{");
for (int i = 0; i < keyCount; i++) {
row.append(i == 0 ? "" : ",").append("\"k").append(i).append("\":").append(i);
}
row.append('}');
String source = "[" + row + "," + row + "]";
JSONArray unlimited = new JSONArray(source,
new JSONParserConfiguration().withMaxSharedKeys(JSONParserConfiguration.UNLIMITED_SHARED_KEYS));
for (int i = 0; i < keyCount; i++) {
assertSame(key(unlimited.getJSONObject(0), "k" + i), key(unlimited.getJSONObject(1), "k" + i));
}
JSONArray limited = new JSONArray(source);
String lastKey = "k" + (keyCount - 1);
assertSame(key(limited.getJSONObject(0), "k0"), key(limited.getJSONObject(1), "k0"));
assertNotSame(key(limited.getJSONObject(0), lastKey), key(limited.getJSONObject(1), lastKey));
assertTrue(unlimited.similar(limited));
}
@Test
public void testSharedKeysNotSharedAcrossParses() {
JSONObject first = new JSONObject("{\"name\": 1}");
JSONObject second = new JSONObject("{\"name\": 2}");
assertNotSame(key(first, "name"), key(second, "name"));
}
@Test
public void testSharedKeysParseUnchanged() {
JSONObject unshared = new JSONObject(SHARED_KEYS_SOURCE, new JSONParserConfiguration().withMaxSharedKeys(0));
JSONObject shared = new JSONObject(SHARED_KEYS_SOURCE);
JSONObject unlimited = new JSONObject(SHARED_KEYS_SOURCE,
new JSONParserConfiguration().withMaxSharedKeys(JSONParserConfiguration.UNLIMITED_SHARED_KEYS));
assertTrue(unshared.similar(shared));
assertTrue(unshared.similar(unlimited));
assertEquals(unshared.toString(), shared.toString());
assertEquals(unshared.toString(), unlimited.toString());
JSONObject row = shared.getJSONArray("rows").getJSONObject(0);
assertEquals(Integer.class, row.get("count").getClass());
assertEquals(Long.class, row.get("big").getClass());
assertEquals(java.math.BigDecimal.class, row.get("ratio").getClass());
assertEquals(Boolean.TRUE, row.get("flag"));
assertSame(JSONObject.NULL, row.get("missing"));
assertSame(JSONObject.NULL, row.getJSONObject("nested").getJSONArray("list").get(2));
assertEquals("third", shared.getJSONArray("rows").getJSONObject(2).get("name"));
}
@Test
public void testSharedKeysLenientSyntax() {
JSONArray rows = new JSONArray("[{\"name\": 1, \"count\": 2}, {'name': 'single', count: 3}]",
new JSONParserConfiguration().withStrictMode(false));
assertSame(key(rows.getJSONObject(0), "name"), key(rows.getJSONObject(1), "name"));
assertSame(key(rows.getJSONObject(0), "count"), key(rows.getJSONObject(1), "count"));
assertEquals("single", rows.getJSONObject(1).get("name"));
}
@Test
public void testSharedKeysStrictMode() {
JSONArray rows = new JSONArray("[{\"a\": 1}, {\"a\": 2}]", new JSONParserConfiguration().withStrictMode());
assertSame(key(rows.getJSONObject(0), "a"), key(rows.getJSONObject(1), "a"));
assertFalse(rows.getJSONObject(0).similar(rows.getJSONObject(1)));
}
/**
* Returns the key instance a JSONObject holds, rather than the caller's equal String.
*/
private static String key(JSONObject jsonObject, String name) {
for (String key : jsonObject.keySet()) {
if (key.equals(name)) {
return key;
}
}
fail("missing key " + name);
return null;
}
} }
@@ -98,6 +98,50 @@ public class JSONPointerTest {
assertEquals(8, query("/m~0n")); assertEquals(8, query("/m~0n"));
} }
@Test
public void escapeSequencesInObjectKeys() {
JSONObject object = new JSONObject().put("~1", "tilde one").put("/", "slash")
.put("~0", "tilde zero").put("~", "tilde");
assertEquals("tilde one", object.query("/~01"));
assertEquals("tilde zero", object.query("/~00"));
assertEquals("tilde one", object.query("#/~01"));
assertEquals("tilde zero", object.query("#/~00"));
}
@Test
public void builderPreservesLiteralTokens() {
JSONObject object = new JSONObject().put("~1", "tilde one").put("/", "slash")
.put("~0", "tilde zero").put("~", "tilde");
assertEquals("tilde one", JSONPointer.builder().append("~1").build().queryFrom(object));
assertEquals("tilde zero", JSONPointer.builder().append("~0").build().queryFrom(object));
}
@Test
public void tokenListPreservesLiteralTokens() {
JSONObject object = new JSONObject().put("~1", "tilde one").put("/", "slash")
.put("~0", "tilde zero").put("~", "tilde");
assertEquals("tilde one", new JSONPointer(java.util.Arrays.asList("~1")).queryFrom(object));
assertEquals("tilde zero", new JSONPointer(java.util.Arrays.asList("~0")).queryFrom(object));
}
@Test
public void escapedTildeTokensSelectLiteralKeys() {
JSONObject object = new JSONObject().put("~1", "literal ~1").put("/", "slash")
.put("~0", "literal ~0").put("~", "tilde")
.put("a~1b", "literal a~1b").put("a/b", "a slash b")
.put("a~0b", "literal a~0b").put("a~b", "a tilde b");
assertEquals("literal ~1", object.query("/~01"));
assertEquals("literal ~1", object.query("#/~01"));
assertEquals("literal ~0", object.query("/~00"));
assertEquals("literal ~0", object.query("#/~00"));
assertEquals("literal a~1b", object.query("/a~01b"));
assertEquals("literal a~0b", object.query("/a~00b"));
assertEquals("literal ~1", JSONPointer.builder().append("~1").build().queryFrom(object));
assertEquals("literal ~0", JSONPointer.builder().append("~0").build().queryFrom(object));
assertEquals("literal ~1", new JSONPointer(java.util.Arrays.asList("~1")).queryFrom(object));
}
/** /**
* We pass backslashes as-is * We pass backslashes as-is
* *
@@ -141,6 +185,41 @@ public class JSONPointerTest {
assertEquals(8, query("#/m~0n")); assertEquals(8, query("#/m~0n"));
} }
@Test
public void uriFragmentPreservesLiteralPlus() {
JSONObject object = new JSONObject().put("a+b", "plus").put("a b", "space")
.put("a%2Bb", "percent");
assertEquals("plus", object.query("#/a+b"));
assertEquals("plus", object.query("#/a%2Bb"));
assertEquals("space", object.query("#/a%20b"));
assertEquals("percent", object.query("#/a%252Bb"));
assertEquals("plus", object.query("/a+b"));
}
@Test
public void uriFragmentEncodesSpaces() {
JSONObject object = new JSONObject().put("a+b", "plus").put("a b", "space");
JSONPointer plus = JSONPointer.builder().append("a+b").build();
JSONPointer space = JSONPointer.builder().append("a b").build();
assertEquals("#/a%2Bb", plus.toURIFragment());
assertEquals("#/a%20b", space.toURIFragment());
assertEquals("#/%20", new JSONPointer("/ ").toURIFragment());
assertEquals("plus", object.query(plus.toURIFragment()));
assertEquals("space", object.query(space.toURIFragment()));
}
@Test
public void uriFragmentPreservesUtf8AndPointerEscapes() {
String key = "\u4e2d +/~1";
JSONObject object = new JSONObject().put(key, "expected")
.put("\u4e2d /~1", "wrong space");
assertEquals("expected", object.query("#/%E4%B8%AD%20+~1~01"));
assertEquals("expected", object.query("#/%E4%B8%AD%20%2B%7E1%7E01"));
JSONPointer pointer = JSONPointer.builder().append(key).build();
assertEquals("#/%E4%B8%AD%20%2B%7E1%7E01", pointer.toURIFragment());
assertEquals("expected", object.query(pointer.toURIFragment()));
}
@SuppressWarnings("unused") @SuppressWarnings("unused")
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void syntaxError() { public void syntaxError() {
@@ -193,9 +272,29 @@ public class JSONPointerTest {
assertEquals("#/c%25d", new JSONPointer("/c%d").toURIFragment()); assertEquals("#/c%25d", new JSONPointer("/c%d").toURIFragment());
assertEquals("#/e%5Ef", new JSONPointer("/e^f").toURIFragment()); assertEquals("#/e%5Ef", new JSONPointer("/e^f").toURIFragment());
assertEquals("#/g%7Ch", new JSONPointer("/g|h").toURIFragment()); assertEquals("#/g%7Ch", new JSONPointer("/g|h").toURIFragment());
assertEquals("#/m%7En", new JSONPointer("/m~n").toURIFragment()); assertEquals("#/m%7E0n", new JSONPointer("/m~n").toURIFragment());
} }
@Test
public void toURIFragmentEscaping() {
JSONPointer pointer = JSONPointer.builder()
.append("obj")
.append("other~key").append("another/key")
.append(0)
.build();
assertEquals("#/obj/other%7E0key/another%7E1key/0", pointer.toURIFragment());
assertEquals("val", new JSONPointer(pointer.toURIFragment()).queryFrom(document));
}
@Test
public void toURIFragmentRoundTrip() {
JSONObject object = new JSONObject().put("~1", "tilde one").put("/", "slash");
JSONPointer tildeOne = JSONPointer.builder().append("~1").build();
JSONPointer slash = JSONPointer.builder().append("/").build();
assertEquals("tilde one", object.query(tildeOne.toURIFragment()));
assertEquals("slash", object.query(slash.toURIFragment()));
}
@Test @Test
public void tokenListIsCopiedInConstructor() { public void tokenListIsCopiedInConstructor() {
JSONPointer.Builder b = JSONPointer.builder().append("key1"); JSONPointer.Builder b = JSONPointer.builder().append("key1");
@@ -16,10 +16,7 @@ import java.io.InputStreamReader;
import java.io.Reader; import java.io.Reader;
import java.io.StringReader; import java.io.StringReader;
import org.json.JSONArray; import org.json.*;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.junit.Test; import org.junit.Test;
/** /**
@@ -98,7 +95,17 @@ public class JSONTokenerTest {
checkValid(" [] ",JSONArray.class); checkValid(" [] ",JSONArray.class);
checkValid("[1,2]",JSONArray.class); checkValid("[1,2]",JSONArray.class);
checkValid("\n\n[1,2]\n\n",JSONArray.class); checkValid("\n\n[1,2]\n\n",JSONArray.class);
checkValid("1 2", String.class);
// Test should fail if default strictMode is true, pass if false
JSONParserConfiguration jsonParserConfiguration = new JSONParserConfiguration();
if (jsonParserConfiguration.isStrictMode()) {
try {
checkValid("1 2", String.class);
assertEquals("Expected to throw exception due to invalid string", true, false);
} catch (JSONException e) { }
} else {
checkValid("1 2", String.class);
}
} }
@Test @Test
@@ -325,4 +332,42 @@ public class JSONTokenerTest {
assertEquals("Stream closed", exception.getMessage()); assertEquals("Stream closed", exception.getMessage());
} }
} }
@Test
public void testInvalidInput_JSONObject_withoutStrictModel_shouldParseInput() {
String input = "{\"invalidInput\": [],}";
JSONTokener tokener = new JSONTokener(input);
// Test should fail if default strictMode is true, pass if false
JSONParserConfiguration jsonParserConfiguration = new JSONParserConfiguration();
if (jsonParserConfiguration.isStrictMode()) {
try {
Object value = tokener.nextValue();
assertEquals(new JSONObject(input).toString(), value.toString());
assertEquals("Expected to throw exception due to invalid string", true, false);
} catch (JSONException e) { }
} else {
Object value = tokener.nextValue();
assertEquals(new JSONObject(input).toString(), value.toString());
}
}
@Test
public void testInvalidInput_JSONArray_withoutStrictModel_shouldParseInput() {
String input = "[\"invalidInput\",]";
JSONTokener tokener = new JSONTokener(input);
// Test should fail if default strictMode is true, pass if false
JSONParserConfiguration jsonParserConfiguration = new JSONParserConfiguration();
if (jsonParserConfiguration.isStrictMode()) {
try {
Object value = tokener.nextValue();
assertEquals(new JSONArray(input).toString(), value.toString());
assertEquals("Expected to throw exception due to invalid string", true, false);
} catch (JSONException e) { }
} else {
Object value = tokener.nextValue();
assertEquals(new JSONArray(input).toString(), value.toString());
}
}
} }
+28 -1
View File
@@ -17,6 +17,33 @@ import org.junit.Test;
*/ */
public class PropertyTest { public class PropertyTest {
@Test
public void shouldIncludeInheritedPropertiesWithoutLocalEntries() {
Properties defaults = new Properties();
defaults.setProperty("timeout", "30");
Properties properties = new Properties(new Properties(defaults));
JSONObject jsonObject = Property.toJSONObject(properties);
assertEquals(1, jsonObject.length());
assertEquals("30", jsonObject.getString("timeout"));
}
@Test
public void shouldPreferLocalPropertiesOverDefaults() {
Properties defaults = new Properties();
defaults.setProperty("timeout", "30");
defaults.setProperty("host", "localhost");
Properties properties = new Properties(defaults);
properties.setProperty("timeout", "60");
JSONObject jsonObject = Property.toJSONObject(properties);
assertEquals(2, jsonObject.length());
assertEquals("60", jsonObject.getString("timeout"));
assertEquals("localhost", jsonObject.getString("host"));
}
/** /**
* JSONObject from null properties object should * JSONObject from null properties object should
* result in an empty JSONObject. * result in an empty JSONObject.
@@ -99,4 +126,4 @@ public class PropertyTest {
assertTrue("property objects should match", assertTrue("property objects should match",
properties.equals(jsonProperties)); properties.equals(jsonProperties));
} }
} }
@@ -574,15 +574,18 @@ public class XMLConfigurationTest {
XMLParserConfiguration keepStringsAndCloseEmptyTag = keepStrings.withCloseEmptyTag(true); XMLParserConfiguration keepStringsAndCloseEmptyTag = keepStrings.withCloseEmptyTag(true);
XMLParserConfiguration keepDigits = keepStringsAndCloseEmptyTag.withKeepStrings(false); XMLParserConfiguration keepDigits = keepStringsAndCloseEmptyTag.withKeepStrings(false);
XMLParserConfiguration keepDigitsAndNoCloseEmptyTag = keepDigits.withCloseEmptyTag(false); XMLParserConfiguration keepDigitsAndNoCloseEmptyTag = keepDigits.withCloseEmptyTag(false);
assertTrue(keepStrings.isKeepStrings()); assertTrue(keepStrings.isKeepNumberAsString());
assertTrue(keepStrings.isKeepBooleanAsString());
assertFalse(keepStrings.isCloseEmptyTag()); assertFalse(keepStrings.isCloseEmptyTag());
assertTrue(keepStringsAndCloseEmptyTag.isKeepStrings()); assertTrue(keepStringsAndCloseEmptyTag.isKeepNumberAsString());
assertTrue(keepStringsAndCloseEmptyTag.isKeepBooleanAsString());
assertTrue(keepStringsAndCloseEmptyTag.isCloseEmptyTag()); assertTrue(keepStringsAndCloseEmptyTag.isCloseEmptyTag());
assertFalse(keepDigits.isKeepStrings()); assertFalse(keepDigits.isKeepNumberAsString());
assertFalse(keepDigits.isKeepBooleanAsString());
assertTrue(keepDigits.isCloseEmptyTag()); assertTrue(keepDigits.isCloseEmptyTag());
assertFalse(keepDigitsAndNoCloseEmptyTag.isKeepStrings()); assertFalse(keepDigitsAndNoCloseEmptyTag.isKeepNumberAsString());
assertFalse(keepDigitsAndNoCloseEmptyTag.isKeepBooleanAsString());
assertFalse(keepDigitsAndNoCloseEmptyTag.isCloseEmptyTag()); assertFalse(keepDigitsAndNoCloseEmptyTag.isCloseEmptyTag());
} }
/** /**
@@ -767,6 +770,67 @@ public class XMLConfigurationTest {
Util.compareActualVsExpectedJsonObjects(actualJsonOutput,expected); Util.compareActualVsExpectedJsonObjects(actualJsonOutput,expected);
} }
/**
* JSON string lost leading zero and converted "True" to true.
*/
@Test
public void testToJSONArray_jsonOutput_withKeepNumberAsString() {
final String originalXml = "<root><id>01</id><id>1</id><id>00</id><id>0</id><id>null</id><item id=\"01\"/><title>True</title></root>";
final JSONObject expected = new JSONObject("{\"root\":{\"item\":{\"id\":\"01\"},\"id\":[\"01\",\"1\",\"00\",\"0\",null],\"title\":true}}");
final JSONObject actualJsonOutput = XML.toJSONObject(originalXml,
new XMLParserConfiguration().withKeepNumberAsString(true));
Util.compareActualVsExpectedJsonObjects(actualJsonOutput,expected);
}
/**
* JSON string lost leading zero and converted "True" to true.
*/
@Test
public void testToJSONArray_jsonOutput_withKeepBooleanAsString() {
final String originalXml = "<root><id>01</id><id>1</id><id>00</id><id>0</id><id>null</id><item id=\"01\"/><title>True</title></root>";
final JSONObject expected = new JSONObject("{\"root\":{\"item\":{\"id\":\"01\"},\"id\":[\"01\",1,\"00\",0,null],\"title\":\"True\"}}");
final JSONObject actualJsonOutput = XML.toJSONObject(originalXml,
new XMLParserConfiguration().withKeepBooleanAsString(true));
Util.compareActualVsExpectedJsonObjects(actualJsonOutput,expected);
}
/**
* null is "null" when keepStrings == true
*/
@Test
public void testToJSONArray_jsonOutput_null_withKeepString() {
final String originalXml = "<root><id>01</id><id>1</id><id>00</id><id>0</id><item id=\"01\"/><title>null</title></root>";
final JSONObject expected = new JSONObject("{\"root\":{\"item\":{\"id\":\"01\"},\"id\":[\"01\",\"1\",\"00\",\"0\"],\"title\":\"null\"}}");
final JSONObject actualJsonOutput = XML.toJSONObject(originalXml,
new XMLParserConfiguration().withKeepStrings(true));
Util.compareActualVsExpectedJsonObjects(actualJsonOutput,expected);
}
/**
* Test keepStrings behavior when setting keepBooleanAsString, keepNumberAsString
*/
@Test
public void test_keepStringBehavior() {
XMLParserConfiguration xpc = new XMLParserConfiguration().withKeepStrings(true);
assertEquals(xpc.isKeepStrings(), true);
xpc = xpc.withKeepBooleanAsString(true);
xpc = xpc.withKeepNumberAsString(false);
assertEquals(xpc.isKeepStrings(), false);
xpc = xpc.withKeepBooleanAsString(false);
xpc = xpc.withKeepNumberAsString(true);
assertEquals(xpc.isKeepStrings(), false);
xpc = xpc.withKeepBooleanAsString(true);
xpc = xpc.withKeepNumberAsString(true);
assertEquals(xpc.isKeepStrings(), true);
xpc = xpc.withKeepBooleanAsString(false);
xpc = xpc.withKeepNumberAsString(false);
assertEquals(xpc.isKeepStrings(), false);
}
/** /**
* JSON string cannot be reverted to original xml. * JSON string cannot be reverted to original xml.
*/ */
@@ -1028,7 +1092,7 @@ public class XMLConfigurationTest {
"<addresses></addresses>"; "<addresses></addresses>";
String expectedStr = String expectedStr =
"{\"addresses\":[]}"; "{\"addresses\":[\"\"]}";
Set<String> forceList = new HashSet<String>(); Set<String> forceList = new HashSet<String>();
forceList.add("addresses"); forceList.add("addresses");
@@ -1066,7 +1130,7 @@ public class XMLConfigurationTest {
"<addresses />"; "<addresses />";
String expectedStr = String expectedStr =
"{\"addresses\":[]}"; "{\"addresses\":[\"\"]}";
Set<String> forceList = new HashSet<String>(); Set<String> forceList = new HashSet<String>();
forceList.add("addresses"); forceList.add("addresses");
@@ -1080,6 +1144,157 @@ public class XMLConfigurationTest {
Util.compareActualVsExpectedJsonObjects(jsonObject, expetedJsonObject); Util.compareActualVsExpectedJsonObjects(jsonObject, expetedJsonObject);
} }
@Test
public void testForceListWithLastElementAsEmptyTag(){
final String originalXml = "<root><id>1</id><id/></root>";
final String expectedJsonString = "{\"root\":{\"id\":[1,\"\"]}}";
HashSet<String> forceListCandidates = new HashSet<>();
forceListCandidates.add("id");
final JSONObject json = XML.toJSONObject(originalXml,
new XMLParserConfiguration()
.withKeepStrings(false)
.withcDataTagName("content")
.withForceList(forceListCandidates)
.withConvertNilAttributeToNull(true));
assertEquals(expectedJsonString, json.toString());
}
@Test
public void testForceListWithFirstElementAsEmptyTag(){
final String originalXml = "<root><id/><id>1</id></root>";
final String expectedJsonString = "{\"root\":{\"id\":[\"\",1]}}";
HashSet<String> forceListCandidates = new HashSet<>();
forceListCandidates.add("id");
final JSONObject json = XML.toJSONObject(originalXml,
new XMLParserConfiguration()
.withKeepStrings(false)
.withcDataTagName("content")
.withForceList(forceListCandidates)
.withConvertNilAttributeToNull(true));
assertEquals(expectedJsonString, json.toString());
}
@Test
public void testForceListWithMiddleElementAsEmptyTag(){
final String originalXml = "<root><id>1</id><id/><id>2</id></root>";
final String expectedJsonString = "{\"root\":{\"id\":[1,\"\",2]}}";
HashSet<String> forceListCandidates = new HashSet<>();
forceListCandidates.add("id");
final JSONObject json = XML.toJSONObject(originalXml,
new XMLParserConfiguration()
.withKeepStrings(false)
.withcDataTagName("content")
.withForceList(forceListCandidates)
.withConvertNilAttributeToNull(true));
assertEquals(expectedJsonString, json.toString());
}
@Test
public void testForceListWithLastElementAsEmpty(){
final String originalXml = "<root><id>1</id><id></id></root>";
final String expectedJsonString = "{\"root\":{\"id\":[1,\"\"]}}";
HashSet<String> forceListCandidates = new HashSet<>();
forceListCandidates.add("id");
final JSONObject json = XML.toJSONObject(originalXml,
new XMLParserConfiguration()
.withKeepStrings(false)
.withForceList(forceListCandidates)
.withConvertNilAttributeToNull(true));
assertEquals(expectedJsonString, json.toString());
}
@Test
public void testForceListWithFirstElementAsEmpty(){
final String originalXml = "<root><id></id><id>1</id></root>";
final String expectedJsonString = "{\"root\":{\"id\":[\"\",1]}}";
HashSet<String> forceListCandidates = new HashSet<>();
forceListCandidates.add("id");
final JSONObject json = XML.toJSONObject(originalXml,
new XMLParserConfiguration()
.withKeepStrings(false)
.withForceList(forceListCandidates)
.withConvertNilAttributeToNull(true));
assertEquals(expectedJsonString, json.toString());
}
@Test
public void testForceListWithMiddleElementAsEmpty(){
final String originalXml = "<root><id>1</id><id></id><id>2</id></root>";
final String expectedJsonString = "{\"root\":{\"id\":[1,\"\",2]}}";
HashSet<String> forceListCandidates = new HashSet<>();
forceListCandidates.add("id");
final JSONObject json = XML.toJSONObject(originalXml,
new XMLParserConfiguration()
.withKeepStrings(false)
.withForceList(forceListCandidates)
.withConvertNilAttributeToNull(true));
assertEquals(expectedJsonString, json.toString());
}
@Test
public void testForceListEmptyAndEmptyTagsMixed(){
final String originalXml = "<root><id></id><id/><id>1</id><id/><id></id><id>2</id></root>";
final String expectedJsonString = "{\"root\":{\"id\":[\"\",\"\",1,\"\",\"\",2]}}";
HashSet<String> forceListCandidates = new HashSet<>();
forceListCandidates.add("id");
final JSONObject json = XML.toJSONObject(originalXml,
new XMLParserConfiguration()
.withKeepStrings(false)
.withForceList(forceListCandidates)
.withConvertNilAttributeToNull(true));
assertEquals(expectedJsonString, json.toString());
}
@Test
public void testForceListConsistencyWithDefault() {
final String originalXml = "<root><id>0</id><id>1</id><id/><id></id></root>";
final String expectedJsonString = "{\"root\":{\"id\":[0,1,\"\",\"\"]}}";
// confirm expected result of default array-of-tags processing
JSONObject json = XML.toJSONObject(originalXml);
assertEquals(expectedJsonString, json.toString());
// confirm forceList array-of-tags processing is consistent with default processing
HashSet<String> forceListCandidates = new HashSet<>();
forceListCandidates.add("id");
json = XML.toJSONObject(originalXml,
new XMLParserConfiguration()
.withForceList(forceListCandidates));
assertEquals(expectedJsonString, json.toString());
}
@Test
public void testForceListInitializesAnArrayWithAnEmptyElement(){
final String originalXml = "<root><id></id></root>";
final String expectedJsonString = "{\"root\":{\"id\":[\"\"]}}";
HashSet<String> forceListCandidates = new HashSet<>();
forceListCandidates.add("id");
JSONObject json = XML.toJSONObject(originalXml,
new XMLParserConfiguration()
.withForceList(forceListCandidates));
assertEquals(expectedJsonString, json.toString());
}
@Test
public void testForceListInitializesAnArrayWithAnEmptyTag(){
final String originalXml = "<root><id/></root>";
final String expectedJsonString = "{\"root\":{\"id\":[\"\"]}}";
HashSet<String> forceListCandidates = new HashSet<>();
forceListCandidates.add("id");
JSONObject json = XML.toJSONObject(originalXml,
new XMLParserConfiguration()
.withForceList(forceListCandidates));
assertEquals(expectedJsonString, json.toString());
}
@Test @Test
public void testMaxNestingDepthIsSet() { public void testMaxNestingDepthIsSet() {
XMLParserConfiguration xmlParserConfiguration = XMLParserConfiguration.ORIGINAL; XMLParserConfiguration xmlParserConfiguration = XMLParserConfiguration.ORIGINAL;
+255
View File
@@ -7,6 +7,7 @@ Public Domain.
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@@ -565,6 +566,42 @@ public class XMLTest {
assertTrue("Illegal@node",result.contains("<Illegal@node>someValue2</Illegal@node>")); assertTrue("Illegal@node",result.contains("<Illegal@node>someValue2</Illegal@node>"));
} }
/**
* A JSON key containing XML metacharacters must not be emitted as a raw
* tag name, since doing so allows the key to break out of its element and
* inject sibling structure into the output (CWE-91, issue #1071).
*/
@Test
public void toStringRejectsElementInjectionInKey()
{
JSONObject jo = new JSONObject(
"{\"a/><injected>evil</injected><a\":\"\"}");
try {
XML.toString(jo, "root");
fail("expected JSONException for key containing XML metacharacters");
} catch (JSONException expected) {
// expected: '/', '<', '>' are rejected in element names
}
// caller-supplied tagName is checked too
try {
XML.toString(new JSONObject(), "bad<tag");
fail("expected JSONException for tagName containing '<'");
} catch (JSONException expected) {
// expected: '<' is rejected in element names
}
// each metacharacter is rejected individually
for (char c : new char[] {'<', '>', '&', '"', '\'', '/'}) {
try {
XML.toString(new JSONObject().put("a" + c + "b", "v"));
fail("expected JSONException for key containing '" + c + "'");
} catch (JSONException expected) {
// expected
}
}
}
/** /**
* JSONObject with NULL value, to XML.toString() * JSONObject with NULL value, to XML.toString()
*/ */
@@ -1426,6 +1463,224 @@ public class XMLTest {
assertEquals(jsonObject3.getJSONObject("color").getString("value"), "008E97"); assertEquals(jsonObject3.getJSONObject("color").getString("value"), "008E97");
} }
/**
* Tests that empty numeric character reference &#; throws JSONException.
* Previously threw StringIndexOutOfBoundsException.
* Related to issue #1035
*/
@Test(expected = JSONException.class)
public void testEmptyNumericEntityThrowsJSONException() {
String xmlStr = "<a>&#;</a>";
XML.toJSONObject(xmlStr);
}
/**
* Tests that malformed decimal entity &#txx; throws JSONException.
* Previously threw NumberFormatException.
* Related to issue #1036
*/
@Test(expected = JSONException.class)
public void testInvalidDecimalEntityThrowsJSONException() {
String xmlStr = "<a>&#txx;</a>";
XML.toJSONObject(xmlStr);
}
/**
* Tests that empty hex entity &#x; throws JSONException.
* Validates proper input validation for hex entities.
*/
@Test(expected = JSONException.class)
public void testEmptyHexEntityThrowsJSONException() {
String xmlStr = "<a>&#x;</a>";
XML.toJSONObject(xmlStr);
}
/**
* Tests that invalid hex entity &#xGGG; throws JSONException.
* Validates hex digit validation.
*/
@Test(expected = JSONException.class)
public void testInvalidHexEntityThrowsJSONException() {
String xmlStr = "<a>&#xGGG;</a>";
XML.toJSONObject(xmlStr);
}
/**
* Tests that out-of-range hex entities throw JSONException rather than an uncaught runtime exception.
*/
@Test(expected = JSONException.class)
public void testOutOfRangeHexEntityThrowsJSONException() {
String xmlStr = "<a>&#x110000;</a>";
XML.toJSONObject(xmlStr);
}
/**
* Tests that out-of-range decimal entities throw JSONException rather than an uncaught runtime exception.
*/
@Test(expected = JSONException.class)
public void testOutOfRangeDecimalEntityThrowsJSONException() {
String xmlStr = "<a>&#1114112;</a>";
XML.toJSONObject(xmlStr);
}
/**
* Tests that surrogate code point entities throw JSONException.
*/
@Test(expected = JSONException.class)
public void testSurrogateHexEntityThrowsJSONException() {
String xmlStr = "<a>&#xD800;</a>";
XML.toJSONObject(xmlStr);
}
/**
* Tests that out-of-range numeric entities in attribute values throw JSONException.
*/
@Test(expected = JSONException.class)
public void testOutOfRangeHexEntityInAttributeThrowsJSONException() {
String xmlStr = "<a b=\"&#x110000;\"/>";
XML.toJSONObject(xmlStr);
}
/**
* Tests that valid decimal numeric entity &#65; works correctly.
* Should decode to character 'A'.
*/
@Test
public void testValidDecimalEntity() {
String xmlStr = "<a>&#65;</a>";
JSONObject jsonObject = XML.toJSONObject(xmlStr);
assertEquals("A", jsonObject.getString("a"));
}
/**
* Tests that valid hex numeric entity &#x41; works correctly.
* Should decode to character 'A'.
*/
@Test
public void testValidHexEntity() {
String xmlStr = "<a>&#x41;</a>";
JSONObject jsonObject = XML.toJSONObject(xmlStr);
assertEquals("A", jsonObject.getString("a"));
}
/**
* Tests that valid uppercase hex entity &#X41; works correctly.
* Should decode to character 'A'.
*/
@Test
public void testValidUppercaseHexEntity() {
String xmlStr = "<a>&#X41;</a>";
JSONObject jsonObject = XML.toJSONObject(xmlStr);
assertEquals("A", jsonObject.getString("a"));
}
/**
* Tests that valid XML numeric character references for whitespace
* control characters (TAB, LF, CR) are correctly unescaped. These
* codepoints are explicitly allowed by the XML 1.0 spec
* (https://www.w3.org/TR/REC-xml/#charsets) but were previously rejected
* as invalid. See issue #1059.
*/
@Test
public void testValidWhitespaceNumericEntityUnescape() {
// decimal references for the three allowed control characters
assertEquals("\t", XML.unescape("&#9;"));
assertEquals("\n", XML.unescape("&#10;"));
assertEquals("\r", XML.unescape("&#13;"));
// hex references for the same codepoints
assertEquals("\t", XML.unescape("&#x9;"));
assertEquals("\n", XML.unescape("&#xA;"));
assertEquals("\r", XML.unescape("&#xD;"));
}
/**
* Tests that {@code XML.toJSONObject} accepts numeric character references
* for the XML-allowed control characters (TAB, LF, CR) without throwing.
* Regression test for #1059, where {@code XML.toJSONObject("<a>&#10;</a>")}
* threw JSONException in versions after 20251224.
*/
@Test
public void testValidWhitespaceNumericEntityToJSONObject() {
// LF reference should round-trip through toJSONObject without throwing
JSONObject jsonObject = XML.toJSONObject("<a>&#10;</a>");
// the value is the LF character (possibly trimmed by the JSON path,
// but the call must not throw)
assertTrue(jsonObject.has("a"));
// TAB and CR references also accepted
XML.toJSONObject("<a>&#9;</a>");
XML.toJSONObject("<a>&#13;</a>");
}
/**
* Tests that numeric character references to C1 control characters are
* still rejected. #x7F-#x9F is inside the XML 1.0 {@code Char} range, but
* this library has always refused those references while parsing
* ({@code &#133;} is NEL, #x85), and fixing the serialization of TAB/LF/CR
* must not change what the parser accepts.
*/
@Test
public void testRejectsC1ControlCharacterReference() {
assertThrows(JSONException.class,
() -> XML.toJSONObject("<name>Joe &#133; Tester</name>"));
// the neighbouring boundary codepoints behave the same way
assertThrows(JSONException.class,
() -> XML.toJSONObject("<name>Joe &#127; Tester</name>"));
assertThrows(JSONException.class,
() -> XML.toJSONObject("<name>Joe &#159; Tester</name>"));
// ... while the characters the parser does accept still work
XML.toJSONObject("<name>Joe &#32; Tester</name>");
}
/**
* Tests that serializing a string value containing literal TAB, LF and CR
* characters writes numeric character references (&amp;#9;, &amp;#10;,
* &amp;#13;) instead of the literal characters. Literal occurrences of
* these characters are subject to whitespace normalization by conforming
* XML parsers, so the original value would be lost when the generated XML
* is read back. Regression test for #1092, where #1070 stopped
* XML.toString() and JSONML.toString() from escaping these characters.
*/
@Test
public void testEscapesLiteralWhitespaceControlCharsOnSerialization() {
// LF in a text node must survive as a numeric character reference
JSONObject jo = new JSONObject().put("value", "Lettuce\nTomato");
String xmlOutput = XML.toString(jo);
assertTrue("XML should escape literal LF to preserve it, got: " + xmlOutput,
xmlOutput.contains("&#xa;"));
// TAB and CR likewise
JSONObject tabJo = new JSONObject().put("value", "a\tb\rc");
String tabXml = XML.toString(tabJo);
assertTrue("XML should escape literal TAB, got: " + tabXml, tabXml.contains("&#x9;"));
assertTrue("XML should escape literal CR, got: " + tabXml, tabXml.contains("&#xd;"));
}
/**
* Tests that the generated XML round-trips: the numeric character
* references produced for TAB/LF/CR are read back by
* {@code XML.toJSONObject} as the original characters.
*/
@Test
public void testWhitespaceControlCharsRoundTripThroughXml() {
String original = "Lettuce\nTomato\tMustard";
JSONObject jo = new JSONObject().put("value", original);
String xmlOutput = XML.toString(jo);
JSONObject reparsed = XML.toJSONObject(xmlOutput);
assertEquals("LF/TAB must survive the XML round trip",
original, reparsed.getString("value"));
}
/**
* Same escaping requirement for {@code JSONML.toString}.
*/
@Test
public void testJSONMLToStringEscapesLiteralNewlines() {
JSONObject jo = new JSONObject("{\"tagName\":\"MyTag\", \"value\":\"Lettuce\\nTomato\"}");
String xmlOutput = JSONML.toString(jo);
assertTrue("JSONML should escape literal LF to preserve it, got: " + xmlOutput,
xmlOutput.contains("&#xa;"));
}
} }
@@ -0,0 +1,81 @@
package org.json.junit;
import org.json.XMLTokener;
import org.junit.Test;
import java.io.StringReader;
import static org.junit.Assert.*;
/**
* Tests for JSON-Java XMLTokener.java
*/
public class XMLTokenerTest {
/**
* Tests that nextCDATA() correctly extracts content from within a CDATA section.
*/
@Test
public void testNextCDATA() {
String xml = "This is <![CDATA[ some <CDATA> content ]]> after";
XMLTokener tokener = new XMLTokener(new StringReader(xml));
tokener.skipPast("<![CDATA[");
String cdata = tokener.nextCDATA();
assertEquals(" some <CDATA> content ", cdata);
}
/**
* Tests that nextContent() returns plain text content before a tag.
*/
@Test
public void testNextContentWithText() {
String xml = "Some content<nextTag>";
XMLTokener tokener = new XMLTokener(xml);
Object content = tokener.nextContent();
assertEquals("Some content", content);
}
/**
* Tests that nextContent() returns '<' character when starting with a tag.
*/
@Test
public void testNextContentWithTag() {
String xml = "<tag>";
XMLTokener tokener = new XMLTokener(xml);
Object content = tokener.nextContent();
assertEquals('<', content);
}
/**
* Tests that nextEntity() resolves a known entity like &amp; correctly.
*/
@Test
public void testNextEntityKnown() {
XMLTokener tokener = new XMLTokener("amp;");
Object result = tokener.nextEntity('&');
assertEquals("&", result);
}
/**
* Tests that nextEntity() preserves unknown entities by returning them unchanged.
*/
@Test
public void testNextEntityUnknown() {
XMLTokener tokener = new XMLTokener("unknown;");
tokener.next(); // skip 'u'
Object result = tokener.nextEntity('&');
assertEquals("&nknown;", result); // malformed start to simulate unknown
}
/**
* Tests skipPast() to ensure the cursor moves past the specified string.
*/
@Test
public void testSkipPast() {
String xml = "Ignore this... endHere more text";
XMLTokener tokener = new XMLTokener(xml);
tokener.skipPast("endHere");
assertEquals(' ', tokener.next()); // should be the space after "endHere"
}
}
@@ -0,0 +1,23 @@
package org.json.junit.data;
public class CustomClass {
public int number;
public String name;
public Long longNumber;
public CustomClass() {}
public CustomClass (int number, String name, Long longNumber) {
this.number = number;
this.name = name;
this.longNumber = longNumber;
}
@Override
public boolean equals(Object o) {
CustomClass customClass = (CustomClass) o;
return (this.number == customClass.number
&& this.name.equals(customClass.name)
&& this.longNumber.equals(customClass.longNumber));
}
}
@@ -0,0 +1,19 @@
package org.json.junit.data;
import java.math.BigInteger;
public class CustomClassA {
public BigInteger largeInt;
public CustomClassA() {}
public CustomClassA(BigInteger largeInt) {
this.largeInt = largeInt;
}
@Override
public boolean equals(Object o) {
CustomClassA classA = (CustomClassA) o;
return this.largeInt.equals(classA.largeInt);
}
}
@@ -0,0 +1,20 @@
package org.json.junit.data;
public class CustomClassB {
public int number;
public CustomClassC classC;
public CustomClassB() {}
public CustomClassB(int number, CustomClassC classC) {
this.number = number;
this.classC = classC;
}
@Override
public boolean equals(Object o) {
CustomClassB classB = (CustomClassB) o;
return this.number == classB.number
&& this.classC.equals(classB.classC);
}
}
@@ -0,0 +1,34 @@
package org.json.junit.data;
import org.json.JSONObject;
public class CustomClassC {
public String stringName;
public Long longNumber;
public CustomClassC() {}
public CustomClassC(String stringName, Long longNumber) {
this.stringName = stringName;
this.longNumber = longNumber;
}
public JSONObject toJSON() {
JSONObject object = new JSONObject();
object.put("stringName", this.stringName);
object.put("longNumber", this.longNumber);
return object;
}
@Override
public boolean equals(Object o) {
CustomClassC classC = (CustomClassC) o;
return this.stringName.equals(classC.stringName)
&& this.longNumber.equals(classC.longNumber);
}
@Override
public int hashCode() {
return java.util.Objects.hash(stringName, longNumber);
}
}
@@ -0,0 +1,19 @@
package org.json.junit.data;
import java.util.List;
public class CustomClassD {
public List<String> stringList;
public CustomClassD() {}
public CustomClassD(List<String> stringList) {
this.stringList = stringList;
}
@Override
public boolean equals(Object o) {
CustomClassD classD = (CustomClassD) o;
return this.stringList.equals(classD.stringList);
}
}
@@ -0,0 +1,18 @@
package org.json.junit.data;
import java.util.List;
public class CustomClassE {
public List<CustomClassC> listClassC;
public CustomClassE() {}
public CustomClassE(List<CustomClassC> listClassC) {
this.listClassC = listClassC;
}
@Override
public boolean equals(Object o) {
CustomClassE classE = (CustomClassE) o;
return this.listClassC.equals(classE.listClassC);
}
}
@@ -0,0 +1,19 @@
package org.json.junit.data;
import java.util.List;
public class CustomClassF {
public List<List<String>> listOfString;
public CustomClassF() {}
public CustomClassF(List<List<String>> listOfString) {
this.listOfString = listOfString;
}
@Override
public boolean equals(Object o) {
CustomClassF classF = (CustomClassF) o;
return this.listOfString.equals(classF.listOfString);
}
}
@@ -0,0 +1,18 @@
package org.json.junit.data;
import java.util.Map;
public class CustomClassG {
public Map<String, String> dataList;
public CustomClassG () {}
public CustomClassG (Map<String, String> dataList) {
this.dataList = dataList;
}
@Override
public boolean equals(Object object) {
CustomClassG classG = (CustomClassG) object;
return this.dataList.equals(classG.dataList);
}
}
@@ -0,0 +1,22 @@
package org.json.junit.data;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
public class CustomClassH {
public Map<String, List<Integer>> integerMap;
public CustomClassH() {}
public CustomClassH(Map<String, List<Integer>> integerMap) {
this.integerMap = integerMap;
}
@Override
public boolean equals(Object object) {
CustomClassH classH = (CustomClassH) object;
return this.integerMap.size() == classH.integerMap.size()
&& this.integerMap.keySet().equals(classH.integerMap.keySet())
&& new ArrayList<>(this.integerMap.values()).equals(new ArrayList<>(classH.integerMap.values()));
}
}
@@ -0,0 +1,12 @@
package org.json.junit.data;
import java.util.Map;
public class CustomClassI {
public Map<String, Map<String, Integer>> integerMap;
public CustomClassI() {}
public CustomClassI(Map<String, Map<String, Integer>> integerMap) {
this.integerMap = integerMap;
}
}
@@ -0,0 +1,10 @@
package org.json.junit.data;
public class CustomClassJ {
public static String classState = "original";
public int number;
public CustomClassJ() {
// Required for JSONObject#fromJson(Class<T>) tests.
}
}
@@ -0,0 +1,39 @@
package org.json.junit.data;
import org.json.JSONPropertyIgnore;
/**
* Bean used to pin down how {@code JSONObject#fromJson(Class)} binds JSON keys
* to fields: {@code privateString} and {@code privateBoolean} are private,
* {@code transientString} is transient, and {@code ignoredGetterBoolean} is
* hidden behind a getter annotated with {@code @JSONPropertyIgnore} (which only
* suppresses the bean to JSONObject direction).
*/
public class FromJsonKeyBindingExample {
public String displayName;
private boolean privateBoolean;
private String privateString;
private transient String transientString;
private boolean ignoredGetterBoolean;
public FromJsonKeyBindingExample() {
// Required for JSONObject#fromJson(Class<T>) tests.
}
public boolean isPrivateBoolean() {
return privateBoolean;
}
public String getPrivateString() {
return privateString;
}
public String getTransientString() {
return transientString;
}
@JSONPropertyIgnore
public boolean isIgnoredGetterBoolean() {
return ignoredGetterBoolean;
}
}
@@ -0,0 +1,31 @@
package org.json.junit.data;
/**
* A test class that mimics Java record accessor patterns.
* Records use accessor methods without get/is prefixes (e.g., name() instead of getName()).
* This class simulates that behavior to test JSONObject's handling of such methods.
*/
public class PersonRecord {
private final String name;
private final int age;
private final boolean active;
public PersonRecord(String name, int age, boolean active) {
this.name = name;
this.age = age;
this.active = active;
}
// Record-style accessors (no "get" or "is" prefix)
public String name() {
return name;
}
public int age() {
return age;
}
public boolean active() {
return active;
}
}