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
This commit is contained in:
Denys Khalitov
2026-09-26 17:19:47 +03:00
parent b55c69e650
commit f875ab2fc7
2 changed files with 23 additions and 3 deletions
+1 -1
View File
@@ -276,7 +276,7 @@ public class JSONPointer {
try {
StringBuilder rval = new StringBuilder("#");
for (String token : this.refTokens) {
rval.append('/').append(URLEncoder.encode(token, ENCODING));
rval.append('/').append(URLEncoder.encode(escape(token), ENCODING));
}
return rval.toString();
} catch (UnsupportedEncodingException e) {
@@ -219,9 +219,29 @@ public class JSONPointerTest {
assertEquals("#/c%25d", new JSONPointer("/c%d").toURIFragment());
assertEquals("#/e%5Ef", new JSONPointer("/e^f").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
public void tokenListIsCopiedInConstructor() {
JSONPointer.Builder b = JSONPointer.builder().append("key1");