From 89617b8bf70a8e0835599190adae17af293c3367 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 17 Nov 2026 15:41:32 +0100 Subject: [PATCH 1/2] feat(java): allow unpaired UTF-16 surrogates in Fory JSON strings Fory JSON rejects a string or name holding a surrogate without its partner on both read and write. Producers that truncate text by UTF-16 length emit such strings, and other Java JSON libraries accept them. Add ForyJsonBuilder.allowUnpairedSurrogates(boolean), disabled by default. When enabled, readers decode each \uXXXX escape on its own and keep raw lone surrogates in String input; UTF-8 input must still be valid UTF-8. Writers emit a lone surrogate as a lowercase \uXXXX escape in String and UTF-8 output. The flag is read only after pairing fails, so non-surrogate text and valid pairs keep their current paths. StringJsonWriter rechecks LATIN1 fitness once in toJson after escaping a lone surrogate, so a UTF16-coded input whose only non-Latin1 char was escaped still yields a compact LATIN1 String. Co-Authored-By: Claude Opus 5.5 --- docs/json/object-mapping.md | 31 ++- .../org/apache/fory/json/ForyJsonBuilder.java | 21 ++ .../java/org/apache/fory/json/JsonConfig.java | 11 + .../apache/fory/json/reader/JsonReader.java | 12 +- .../fory/json/reader/Latin1JsonReader.java | 26 +-- .../fory/json/reader/Utf16JsonReader.java | 67 +++--- .../fory/json/reader/Utf8JsonReader.java | 26 ++- .../apache/fory/json/writer/JsonWriter.java | 11 + .../fory/json/writer/StringJsonWriter.java | 118 +++++----- .../fory/json/writer/Utf8JsonWriter.java | 67 +++--- .../fory/json/JsonAsyncCompilationTest.java | 1 + .../org/apache/fory/json/JsonStringTest.java | 221 ++++++++++++++++++ .../org/apache/fory/json/JsonTestSupport.java | 1 + 13 files changed, 469 insertions(+), 144 deletions(-) diff --git a/docs/json/object-mapping.md b/docs/json/object-mapping.md index c66fe52370..0878684500 100644 --- a/docs/json/object-mapping.md +++ b/docs/json/object-mapping.md @@ -310,6 +310,7 @@ overrides `JsonInclude` on the class, which overrides the builder default. See | `writeNullFields(boolean)` | `false` | Select `ALWAYS` when true or `NON_NULL` when false | | `writeLongAsString(boolean)` | `false` | Write built-in 64-bit integer values as decimal strings | | `escapeNonAscii(boolean)` | `false` | Escape non-ASCII characters in generated JSON strings and names | +| `allowUnpairedSurrogates(boolean)` | `false` | Read and write unpaired UTF-16 surrogates in strings and names | | `byteArrayFormat(JsonByteArray.Format)` | `BASE64` | Default byte-array representation for reading and writing | | `withCodegen(boolean)` | `true` | Enable generated object codecs | | `withAsyncCompilation(boolean)` | `true` | Compile generated codecs asynchronously | @@ -385,14 +386,40 @@ byte[] utf8 = json.toJsonBytes("汉é😀"); The option applies to string and character values, property names, map keys, enum names, and subtype names through all String, UTF-8, stream, and pretty write APIs. Characters above U+007F use lowercase hexadecimal escapes; supplementary characters use two UTF-16 surrogate escapes. -JSON-required escaping is unchanged, and invalid surrogate sequences in strings still fail. -ASCII characters such as `<`, `>`, and `&` are not additionally escaped. +JSON-required escaping is unchanged, and unpaired surrogates in strings still fail unless +[unpaired surrogates](#unpaired-surrogates) are allowed. ASCII characters such as `<`, `>`, and +`&` are not additionally escaped. The setting defaults to `false` and is fixed for each built instance. Reuse two instances when alternating output policies. Pretty output remains a per-call choice, and reading is unaffected. Disabling the option preserves the existing output representation, including any escapes it already uses. +## Unpaired surrogates + +By default, reading or writing a string or name that contains a UTF-16 surrogate without its +partner fails with `ForyJsonException`. Some producers emit such strings, for example after +truncating text in the middle of a surrogate pair. Allow them when the application must accept or +pass on that text: + +```java +import org.apache.fory.json.ForyJson; + +ForyJson json = ForyJson.builder().allowUnpairedSurrogates(true).build(); +String value = json.fromJson("\"a\\ud83d\"", String.class); // "a" followed by U+D83D +String text = json.toJson(value); // "a\ud83d" +``` + +When enabled, reading decodes each `\uXXXX` escape on its own, so an escaped surrogate without its +partner becomes that single `char`. A raw unpaired surrogate in `String` input is kept as is. Byte +and stream input must still be valid UTF-8, which has no encoding for a surrogate. Writing emits +an unpaired surrogate in string and `char` values, property names, and map keys as a lowercase +`\uXXXX` escape through all String, UTF-8, stream, and pretty write APIs, so the output is valid +UTF-8 and reads back to the same value with the option enabled. Surrogate pairs are read and +written as before, and raw JSON values supplied by the caller are still validated. + +The setting defaults to `false` and is fixed for each built instance. + Caller-supplied raw JSON, including `@JsonRawValue`, is preserved verbatim. A document containing raw JSON can therefore still contain non-ASCII characters. Custom codecs should use structured string-writing methods to honor the option; raw writes remain the codec author's responsibility. diff --git a/java/fory-json/src/main/java/org/apache/fory/json/ForyJsonBuilder.java b/java/fory-json/src/main/java/org/apache/fory/json/ForyJsonBuilder.java index 67a3b4a862..1f46fa28a9 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/ForyJsonBuilder.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/ForyJsonBuilder.java @@ -57,6 +57,7 @@ public final class ForyJsonBuilder { private NullHandling onContentNullRead = NullHandling.SET; private boolean writeLongAsString; private boolean escapeNonAscii; + private boolean allowUnpairedSurrogates; private boolean failOnMissingRequiredProperties; private boolean failOnDuplicateProperties; private JsonByteArray.Format byteArrayFormat = JsonByteArray.Format.BASE64; @@ -188,6 +189,25 @@ public ForyJsonBuilder escapeNonAscii(boolean escapeNonAscii) { return this; } + /** + * Accepts unpaired UTF-16 surrogates in JSON strings and names. Disabled by default, so an + * unpaired surrogate fails the read or write. + * + *

When enabled, reading decodes each \uXXXX escape independently: an escaped + * surrogate without its partner becomes that single {@code char} in the decoded value, and a raw + * unpaired surrogate in {@code String} input is kept as is. Byte input must still be valid UTF-8, + * which cannot encode a surrogate. Writing emits an unpaired surrogate in a {@code String} or + * {@code char} value as a lowercase \uXXXX escape, so String, UTF-8, stream, and + * pretty output all read back to the same value. Paired surrogates are read and written as + * before, and raw JSON supplied by the caller is still validated. + * + *

The setting is fixed when {@link #build()} is called. + */ + public ForyJsonBuilder allowUnpairedSurrogates(boolean allowUnpairedSurrogates) { + this.allowUnpairedSurrogates = allowUnpairedSurrogates; + return this; + } + /** * Rejects missing required constructor or factory properties. Disabled by default. * @@ -458,6 +478,7 @@ JsonConfig buildConfig() { onContentNullRead, writeLongAsString, escapeNonAscii, + allowUnpairedSurrogates, failOnMissingRequiredProperties, failOnDuplicateProperties, byteArrayFormat, diff --git a/java/fory-json/src/main/java/org/apache/fory/json/JsonConfig.java b/java/fory-json/src/main/java/org/apache/fory/json/JsonConfig.java index 3f4615baf8..fe9879ffee 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/JsonConfig.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/JsonConfig.java @@ -44,6 +44,7 @@ public final class JsonConfig { private final NullHandling onContentNullRead; private final boolean writeLongAsString; private final boolean escapeNonAscii; + private final boolean allowUnpairedSurrogates; private final boolean failOnMissingRequiredProperties; private final boolean failOnDuplicateProperties; private final JsonByteArray.Format byteArrayFormat; @@ -70,6 +71,7 @@ public final class JsonConfig { NullHandling onContentNullRead, boolean writeLongAsString, boolean escapeNonAscii, + boolean allowUnpairedSurrogates, boolean failOnMissingRequiredProperties, boolean failOnDuplicateProperties, JsonByteArray.Format byteArrayFormat, @@ -93,6 +95,7 @@ public final class JsonConfig { this.onContentNullRead = onContentNullRead; this.writeLongAsString = writeLongAsString; this.escapeNonAscii = escapeNonAscii; + this.allowUnpairedSurrogates = allowUnpairedSurrogates; this.failOnMissingRequiredProperties = failOnMissingRequiredProperties; this.failOnDuplicateProperties = failOnDuplicateProperties; this.byteArrayFormat = Objects.requireNonNull(byteArrayFormat, "byteArrayFormat"); @@ -147,6 +150,14 @@ public boolean escapeNonAscii() { return escapeNonAscii; } + /** + * Returns whether JSON strings and names may contain unpaired UTF-16 surrogates. Reads decode + * each escape independently, and writes escape an unpaired surrogate. + */ + public boolean allowUnpairedSurrogates() { + return allowUnpairedSurrogates; + } + /** Returns whether required creator properties must appear in the input. */ public boolean failOnMissingRequiredProperties() { return failOnMissingRequiredProperties; diff --git a/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java b/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java index 62841c3262..39fc9f80a3 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java @@ -167,6 +167,9 @@ public abstract class JsonReader { }; private final JsonConfig config; + // Strict reads pair every surrogate. Tolerant reads decode each escape or raw char on its own, so + // a valid pair still decodes to the same two chars; check it only after a surrogate is seen. + protected final boolean allowUnpairedSurrogates; private final JsonTypeResolver typeResolver; protected int position; private final int maxDepth; @@ -284,6 +287,7 @@ protected JsonReader(JsonConfig config, JsonTypeResolver typeResolver) { this.config = config; this.typeResolver = Objects.requireNonNull(typeResolver, "typeResolver"); maxDepth = config.maxDepth(); + allowUnpairedSurrogates = config.allowUnpairedSurrogates(); } /** @@ -2821,7 +2825,7 @@ private long readQuotedStringHash() { } if (ch == '\\') { ch = readEscapedFieldNameChar(); - if (Character.isHighSurrogate(ch)) { + if (Character.isHighSurrogate(ch) && !allowUnpairedSurrogates) { if (latin1) { hash = JsonFieldNameHash.hashPacked(value, nameLength); latin1 = false; @@ -2838,7 +2842,7 @@ private long readQuotedStringHash() { } hash = JsonFieldNameHash.update(hash, low); nameLength++; - } else if (Character.isLowSurrogate(ch)) { + } else if (Character.isLowSurrogate(ch) && !allowUnpairedSurrogates) { throw error("Unpaired low surrogate escape"); } else { if (latin1) { @@ -2858,7 +2862,7 @@ private long readQuotedStringHash() { if (ch < 0x20) { throw error("Control character in string"); } - if (Character.isHighSurrogate(ch)) { + if (Character.isHighSurrogate(ch) && !allowUnpairedSurrogates) { if (position >= length() || !Character.isLowSurrogate(charAt(position))) { throw error("Unpaired high surrogate in string"); } @@ -2871,7 +2875,7 @@ private long readQuotedStringHash() { nameLength += 2; continue; } - if (Character.isLowSurrogate(ch)) { + if (Character.isLowSurrogate(ch) && !allowUnpairedSurrogates) { throw error("Unpaired low surrogate in string"); } if (latin1) { diff --git a/java/fory-json/src/main/java/org/apache/fory/json/reader/Latin1JsonReader.java b/java/fory-json/src/main/java/org/apache/fory/json/reader/Latin1JsonReader.java index 59ac763d00..48f4fb11e4 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/reader/Latin1JsonReader.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/reader/Latin1JsonReader.java @@ -191,7 +191,7 @@ protected long scanStringHash(int start, int end) { } else { ch = (char) raw; } - if (Character.isHighSurrogate(ch)) { + if (Character.isHighSurrogate(ch) && !allowUnpairedSurrogates) { if (latin1) { hash = JsonFieldNameHash.hashPacked(value, decodedLength); latin1 = false; @@ -235,7 +235,7 @@ protected boolean matchesScannedString(int start, int end, String expected) { } else { ch = scanSimpleEscape(escaped, cursor - 1); } - if (Character.isHighSurrogate(ch)) { + if (Character.isHighSurrogate(ch) && !allowUnpairedSurrogates) { matches &= index < expected.length() && expected.charAt(index++) == ch; cursor += 2; char low = scanUnicodeEscape(cursor); @@ -267,7 +267,7 @@ protected CharSequence decodeQuotedText(int start, int end) { } else { ch = scanSimpleEscape(escaped, offset - 1); } - if (Character.isHighSurrogate(ch)) { + if (Character.isHighSurrogate(ch) && !allowUnpairedSurrogates) { offset += 2; char low = scanUnicodeEscape(offset); offset += 4; @@ -297,6 +297,9 @@ private int scanEscape(int slash, int inputLength) { } char ch = scanUnicodeEscape(cursor); cursor += 4; + if (!Character.isSurrogate(ch) || allowUnpairedSurrogates) { + return cursor; + } if (Character.isHighSurrogate(ch)) { if (cursor + 6 > inputLength || input[cursor] != '\\' || input[cursor + 1] != 'u') { throw errorAt("Unpaired high surrogate escape", slash); @@ -307,10 +310,7 @@ private int scanEscape(int slash, int inputLength) { } return cursor + 6; } - if (Character.isLowSurrogate(ch)) { - throw errorAt("Unpaired low surrogate escape", slash); - } - return cursor; + throw errorAt("Unpaired low surrogate escape", slash); } private char scanUnicodeEscape(int offset) { @@ -2649,7 +2649,7 @@ private long readQuotedStringHashSlow() { } if (ch == '\\') { char escaped = readEscapedFieldNameChar(); - if (Character.isHighSurrogate(escaped)) { + if (Character.isHighSurrogate(escaped) && !allowUnpairedSurrogates) { if (latin1) { hash = JsonFieldNameHash.hashPacked(value, nameLength); latin1 = false; @@ -2666,7 +2666,7 @@ private long readQuotedStringHashSlow() { } hash = JsonFieldNameHash.update(hash, low); nameLength++; - } else if (Character.isLowSurrogate(escaped)) { + } else if (Character.isLowSurrogate(escaped) && !allowUnpairedSurrogates) { throw error("Unpaired low surrogate escape"); } else { if (latin1) { @@ -2748,7 +2748,7 @@ private String readStringLatin1Tail(byte[] bytes, int out, int ch) { } if (ch == '\\') { char escaped = readEscapedStringChar(); - if (Character.isHighSurrogate(escaped)) { + if (Character.isHighSurrogate(escaped) && !allowUnpairedSurrogates) { char low = readLowSurrogateEscape(); bytes = widenStringDecodeBuffer(bytes, out); out <<= 1; @@ -2757,7 +2757,7 @@ private String readStringLatin1Tail(byte[] bytes, int out, int ch) { out = putUtf16Char(bytes, out, low); return readStringUtf16Tail(bytes, out); } - if (Character.isLowSurrogate(escaped)) { + if (Character.isLowSurrogate(escaped) && !allowUnpairedSurrogates) { throw error("Unpaired low surrogate escape"); } if (escaped <= 0xFF) { @@ -2809,12 +2809,12 @@ private String readStringUtf16Tail(byte[] bytes, int out) { } if (ch == '\\') { char escaped = readEscapedStringChar(); - if (Character.isHighSurrogate(escaped)) { + if (Character.isHighSurrogate(escaped) && !allowUnpairedSurrogates) { char low = readLowSurrogateEscape(); bytes = ensureStringDecodeCapacity(bytes, out + 4); out = putUtf16Char(bytes, out, escaped); out = putUtf16Char(bytes, out, low); - } else if (Character.isLowSurrogate(escaped)) { + } else if (Character.isLowSurrogate(escaped) && !allowUnpairedSurrogates) { throw error("Unpaired low surrogate escape"); } else { bytes = ensureStringDecodeCapacity(bytes, out + 2); diff --git a/java/fory-json/src/main/java/org/apache/fory/json/reader/Utf16JsonReader.java b/java/fory-json/src/main/java/org/apache/fory/json/reader/Utf16JsonReader.java index a7b135b135..484caf6b81 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/reader/Utf16JsonReader.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/reader/Utf16JsonReader.java @@ -127,7 +127,7 @@ protected int scanStringEnd(int start) { cursor = scanEscape(cursor); } else if (Character.isHighSurrogate(ch)) { cursor = scanRawSurrogate(cursor); - } else if (Character.isLowSurrogate(ch)) { + } else if (Character.isLowSurrogate(ch) && !allowUnpairedSurrogates) { throw errorAt("Unpaired low surrogate in string", cursor); } else { cursor++; @@ -146,7 +146,7 @@ protected int scanStringEnd(int start) { cursor = scanEscape(cursor); } else if (Character.isHighSurrogate(ch)) { cursor = scanRawSurrogate(cursor); - } else if (Character.isLowSurrogate(ch)) { + } else if (Character.isLowSurrogate(ch) && !allowUnpairedSurrogates) { throw errorAt("Unpaired low surrogate in string", cursor); } else { cursor++; @@ -174,7 +174,7 @@ protected long scanStringHash(int start, int end) { ch = scanSimpleEscape(escaped, cursor - 1); } } - if (Character.isHighSurrogate(ch)) { + if (Character.isHighSurrogate(ch) && !allowUnpairedSurrogates) { if (latin1) { hash = JsonFieldNameHash.hashPacked(value, decodedLength); latin1 = false; @@ -222,7 +222,7 @@ protected boolean matchesScannedString(int start, int end, String expected) { ch = scanSimpleEscape(escaped, cursor - 1); } matches &= index < expected.length() && expected.charAt(index++) == ch; - if (Character.isHighSurrogate(ch)) { + if (Character.isHighSurrogate(ch) && !allowUnpairedSurrogates) { cursor += 2; char low = scanUnicodeEscape(cursor); cursor += 4; @@ -231,7 +231,7 @@ protected boolean matchesScannedString(int start, int end, String expected) { continue; } matches &= index < expected.length() && expected.charAt(index++) == ch; - if (Character.isHighSurrogate(ch)) { + if (Character.isHighSurrogate(ch) && !allowUnpairedSurrogates) { char low = charAtFast(cursor++); matches &= index < expected.length() && expected.charAt(index++) == low; } @@ -254,7 +254,7 @@ protected CharSequence decodeQuotedText(int start, int end) { } else { ch = scanSimpleEscape(escaped, offset - 1); } - if (Character.isHighSurrogate(ch)) { + if (Character.isHighSurrogate(ch) && !allowUnpairedSurrogates) { offset += 2; char low = scanUnicodeEscape(offset); offset += 4; @@ -263,7 +263,7 @@ protected CharSequence decodeQuotedText(int start, int end) { out = putUtf16Char(outBytes, out, low); continue; } - } else if (Character.isHighSurrogate(ch)) { + } else if (Character.isHighSurrogate(ch) && !allowUnpairedSurrogates) { char low = charAtFast(offset++); outBytes = ensureStringDecodeCapacity(outBytes, out + 4); out = putUtf16Char(outBytes, out, ch); @@ -288,6 +288,9 @@ private int scanEscape(int slash) { } char ch = scanUnicodeEscape(cursor); cursor += 4; + if (!Character.isSurrogate(ch) || allowUnpairedSurrogates) { + return cursor; + } if (Character.isHighSurrogate(ch)) { if (cursor + 6 > length || charAtFast(cursor) != '\\' || charAtFast(cursor + 1) != 'u') { throw errorAt("Unpaired high surrogate escape", slash); @@ -298,14 +301,14 @@ private int scanEscape(int slash) { } return cursor + 6; } - if (Character.isLowSurrogate(ch)) { - throw errorAt("Unpaired low surrogate escape", slash); - } - return cursor; + throw errorAt("Unpaired low surrogate escape", slash); } private int scanRawSurrogate(int cursor) { if (cursor + 1 >= length || !Character.isLowSurrogate(charAtFast(cursor + 1))) { + if (allowUnpairedSurrogates) { + return cursor + 1; + } throw errorAt("Unpaired high surrogate in string", cursor); } return cursor + 2; @@ -1928,7 +1931,7 @@ private String readUtf16StringToken(int start, int offset, boolean nonLatin) { boolean currentNonLatin = nonLatin || nonLatinBytes != 0 && hasNonLatinBeforeStop(word, stop - offset); char ch = charAtFast(stop); - if (Character.isHighSurrogate(ch)) { + if (Character.isSurrogate(ch)) { currentNonLatin = true; } String value = readUtf16StringStop(localBytes, start, stop, currentNonLatin, ch); @@ -1949,7 +1952,7 @@ private String readUtf16StringToken(int start, int offset, boolean nonLatin) { boolean currentNonLatin = nonLatin || nonLatinBytes != 0 && hasNonLatinBeforeStop(word, stop - nextOffset); char ch = charAtFast(stop); - if (Character.isHighSurrogate(ch)) { + if (Character.isSurrogate(ch)) { currentNonLatin = true; } String value = readUtf16StringStop(localBytes, start, stop, currentNonLatin, ch); @@ -1977,7 +1980,7 @@ private String readUtf16StringToken(int start, int offset, boolean nonLatin) { boolean currentNonLatin = nonLatin || nonLatinBytes != 0 && hasNonLatinBeforeStop(word, stop - offset); char ch = charAtFast(stop); - if (Character.isHighSurrogate(ch)) { + if (Character.isSurrogate(ch)) { currentNonLatin = true; } String value = readUtf16StringStop(localBytes, start, stop, currentNonLatin, ch); @@ -2013,12 +2016,20 @@ private String readUtf16StringStop( if (Character.isHighSurrogate(ch)) { int lowOffset = stop + 1; if (lowOffset >= length || !Character.isLowSurrogate(charAtFast(lowOffset))) { + if (allowUnpairedSurrogates) { + position = lowOffset; + return null; + } position = stop; throw error("Unpaired high surrogate in string"); } position = lowOffset + 1; return null; } + if (allowUnpairedSurrogates) { + position = stop + 1; + return null; + } position = stop; throw error("Unpaired low surrogate in string"); } @@ -2078,7 +2089,7 @@ private String readStringLatin1Tail(byte[] outBytes, int out, int ch) { } if (ch == '\\') { char escaped = readEscapedStringChar(); - if (Character.isHighSurrogate(escaped)) { + if (Character.isHighSurrogate(escaped) && !allowUnpairedSurrogates) { char low = readLowSurrogateEscape(); outBytes = widenStringDecodeBuffer(outBytes, out); out <<= 1; @@ -2087,7 +2098,7 @@ private String readStringLatin1Tail(byte[] outBytes, int out, int ch) { out = putUtf16Char(outBytes, out, low); return readStringUtf16Tail(outBytes, out, nextStringChar()); } - if (Character.isLowSurrogate(escaped)) { + if (Character.isLowSurrogate(escaped) && !allowUnpairedSurrogates) { throw error("Unpaired low surrogate escape"); } if (escaped <= 0xFF) { @@ -2102,7 +2113,7 @@ private String readStringLatin1Tail(byte[] outBytes, int out, int ch) { } } else if (ch < 0x20) { throw error("Control character in string"); - } else if (Character.isHighSurrogate((char) ch)) { + } else if (Character.isHighSurrogate((char) ch) && !allowUnpairedSurrogates) { char low = readRawLowSurrogate(); outBytes = widenStringDecodeBuffer(outBytes, out); out <<= 1; @@ -2110,7 +2121,7 @@ private String readStringLatin1Tail(byte[] outBytes, int out, int ch) { out = putUtf16Char(outBytes, out, (char) ch); out = putUtf16Char(outBytes, out, low); return readStringUtf16Tail(outBytes, out, nextStringChar()); - } else if (Character.isLowSurrogate((char) ch)) { + } else if (Character.isLowSurrogate((char) ch) && !allowUnpairedSurrogates) { throw error("Unpaired low surrogate in string"); } else if (ch <= 0xFF) { outBytes = ensureStringDecodeCapacity(outBytes, out + 1); @@ -2158,12 +2169,12 @@ private String readStringUtf16Tail(byte[] outBytes, int out, int ch) { } if (ch == '\\') { char escaped = readEscapedStringChar(); - if (Character.isHighSurrogate(escaped)) { + if (Character.isHighSurrogate(escaped) && !allowUnpairedSurrogates) { char low = readLowSurrogateEscape(); outBytes = ensureStringDecodeCapacity(outBytes, out + 4); out = putUtf16Char(outBytes, out, escaped); out = putUtf16Char(outBytes, out, low); - } else if (Character.isLowSurrogate(escaped)) { + } else if (Character.isLowSurrogate(escaped) && !allowUnpairedSurrogates) { throw error("Unpaired low surrogate escape"); } else { outBytes = ensureStringDecodeCapacity(outBytes, out + 2); @@ -2171,12 +2182,12 @@ private String readStringUtf16Tail(byte[] outBytes, int out, int ch) { } } else if (ch < 0x20) { throw error("Control character in string"); - } else if (Character.isHighSurrogate((char) ch)) { + } else if (Character.isHighSurrogate((char) ch) && !allowUnpairedSurrogates) { char low = readRawLowSurrogate(); outBytes = ensureStringDecodeCapacity(outBytes, out + 4); out = putUtf16Char(outBytes, out, (char) ch); out = putUtf16Char(outBytes, out, low); - } else if (Character.isLowSurrogate((char) ch)) { + } else if (Character.isLowSurrogate((char) ch) && !allowUnpairedSurrogates) { throw error("Unpaired low surrogate in string"); } else { outBytes = ensureStringDecodeCapacity(outBytes, out + 2); @@ -2295,13 +2306,13 @@ private String readStringLoop(int start, boolean nonLatin) { return readEscapedStringTail(start, position - 1, nonLatin); } else if (ch < 0x20) { throw error("Control character in string"); - } else if (Character.isHighSurrogate(ch)) { + } else if (Character.isHighSurrogate(ch) && !allowUnpairedSurrogates) { if (position >= length || !Character.isLowSurrogate(charAtFast(position))) { throw error("Unpaired high surrogate in string"); } position++; nonLatin = true; - } else if (Character.isLowSurrogate(ch)) { + } else if (Character.isLowSurrogate(ch) && !allowUnpairedSurrogates) { throw error("Unpaired low surrogate in string"); } else if (ch > 0xFF) { nonLatin = true; @@ -2862,7 +2873,7 @@ private long readQuotedStringHashToken() { } if (ch == '\\') { ch = readEscapedFieldNameChar(); - if (Character.isHighSurrogate(ch)) { + if (Character.isHighSurrogate(ch) && !allowUnpairedSurrogates) { if (latin1) { hash = JsonFieldNameHash.hashPacked(value, nameLength); latin1 = false; @@ -2881,7 +2892,7 @@ private long readQuotedStringHashToken() { } hash = JsonFieldNameHash.update(hash, low); nameLength++; - } else if (Character.isLowSurrogate(ch)) { + } else if (Character.isLowSurrogate(ch) && !allowUnpairedSurrogates) { throw error("Unpaired low surrogate escape"); } else { if (latin1) { @@ -2901,7 +2912,7 @@ private long readQuotedStringHashToken() { if (ch < 0x20) { throw error("Control character in string"); } - if (Character.isHighSurrogate(ch)) { + if (Character.isHighSurrogate(ch) && !allowUnpairedSurrogates) { if (position >= inputLength || !Character.isLowSurrogate(charAtFast(position))) { throw error("Unpaired high surrogate in string"); } @@ -2914,7 +2925,7 @@ private long readQuotedStringHashToken() { nameLength += 2; continue; } - if (Character.isLowSurrogate(ch)) { + if (Character.isLowSurrogate(ch) && !allowUnpairedSurrogates) { throw error("Unpaired low surrogate in string"); } if (latin1) { diff --git a/java/fory-json/src/main/java/org/apache/fory/json/reader/Utf8JsonReader.java b/java/fory-json/src/main/java/org/apache/fory/json/reader/Utf8JsonReader.java index 828deeee7b..8a4bdd15af 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/reader/Utf8JsonReader.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/reader/Utf8JsonReader.java @@ -254,7 +254,9 @@ protected long scanStringHash(int start, int end) { cursor = (int) (decoded >>> 32); codePoint = (int) decoded; } - if (codePoint <= 0xffff && Character.isHighSurrogate((char) codePoint)) { + if (codePoint <= 0xffff + && Character.isHighSurrogate((char) codePoint) + && !allowUnpairedSurrogates) { if (latin1) { hash = JsonFieldNameHash.hashPacked(value, decodedLength); latin1 = false; @@ -310,7 +312,7 @@ protected boolean matchesScannedString(int start, int end, String expected) { escaped = scanSimpleEscape(escapedByte, cursor - 1); } matches &= index < expected.length() && expected.charAt(index++) == escaped; - if (Character.isHighSurrogate(escaped)) { + if (Character.isHighSurrogate(escaped) && !allowUnpairedSurrogates) { cursor += 2; char low = scanUnicodeEscape(cursor); cursor += 4; @@ -355,7 +357,7 @@ protected CharSequence decodeQuotedText(int start, int end) { } else { ch = scanSimpleEscape(escaped, offset - 1); } - if (Character.isHighSurrogate(ch)) { + if (Character.isHighSurrogate(ch) && !allowUnpairedSurrogates) { offset += 2; char low = scanUnicodeEscape(offset); offset += 4; @@ -400,6 +402,9 @@ private int scanEscape(int slash, int inputLimit) { } char ch = scanUnicodeEscape(cursor); cursor += 4; + if (!Character.isSurrogate(ch) || allowUnpairedSurrogates) { + return cursor; + } if (Character.isHighSurrogate(ch)) { if (cursor + 6 > inputLimit || input[cursor] != '\\' || input[cursor + 1] != 'u') { throw errorAt("Unpaired high surrogate escape", slash); @@ -410,10 +415,7 @@ private int scanEscape(int slash, int inputLimit) { } return cursor + 6; } - if (Character.isLowSurrogate(ch)) { - throw errorAt("Unpaired low surrogate escape", slash); - } - return cursor; + throw errorAt("Unpaired low surrogate escape", slash); } private long scanUtf8CodePoint(int offset) { @@ -4277,7 +4279,7 @@ private long readQuotedStringHashSlow() { position = cursor; b = readEscapedFieldNameChar(); cursor = position; - if (Character.isHighSurrogate((char) b)) { + if (Character.isHighSurrogate((char) b) && !allowUnpairedSurrogates) { if (latin1) { hash = JsonFieldNameHash.hashPacked(value, nameLength); latin1 = false; @@ -4297,7 +4299,7 @@ private long readQuotedStringHashSlow() { nameLength++; continue; } - if (Character.isLowSurrogate((char) b)) { + if (Character.isLowSurrogate((char) b) && !allowUnpairedSurrogates) { throw error("Unpaired low surrogate escape"); } } else { @@ -4385,7 +4387,7 @@ private String readStringLatin1Tail(byte[] bytes, int out, int b) { } if (b == '\\') { char ch = readEscapedStringChar(); - if (Character.isHighSurrogate(ch)) { + if (Character.isHighSurrogate(ch) && !allowUnpairedSurrogates) { char low = readLowSurrogateEscape(); bytes = widenStringDecodeBuffer(bytes, out); out <<= 1; @@ -4394,7 +4396,7 @@ private String readStringLatin1Tail(byte[] bytes, int out, int b) { out = putUtf16Char(bytes, out, low); return readStringUtf16Tail(bytes, out); } - if (Character.isLowSurrogate(ch)) { + if (Character.isLowSurrogate(ch) && !allowUnpairedSurrogates) { throw error("Unpaired low surrogate escape"); } if (ch <= 0xFF) { @@ -4525,7 +4527,7 @@ private String readStringUtf16Tail(byte[] bytes, int out) { this.position = position; char ch = readEscapedStringChar(); position = this.position; - if (!Character.isSurrogate(ch)) { + if (!Character.isSurrogate(ch) || allowUnpairedSurrogates) { if (out + 2 > capacity) { bytes = growStringDecodeBuffer(bytes, out + 2); capacity = bytes.length; diff --git a/java/fory-json/src/main/java/org/apache/fory/json/writer/JsonWriter.java b/java/fory-json/src/main/java/org/apache/fory/json/writer/JsonWriter.java index c0f61003ad..fcc20811c1 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/writer/JsonWriter.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/writer/JsonWriter.java @@ -96,6 +96,9 @@ protected static final class UnicodeEscapes { private final JsonTypeResolver typeResolver; private final int maxDepth; protected final boolean escapeNonAscii; + // Tolerant writers emit an unpaired surrogate as a six-character escape. Check it only after + // pairing fails so paired and non-surrogate output keeps the strict path. + protected final boolean allowUnpairedSurrogates; protected boolean prettyPrint; // Indentation is emitted with the opening delimiter, including for custom codecs that omit // writeComma(0). Only the newest container can still be empty; closing it clears this marker. @@ -107,6 +110,14 @@ protected static final class UnicodeEscapes { this.typeResolver = Objects.requireNonNull(typeResolver, "typeResolver"); maxDepth = config.maxDepth(); escapeNonAscii = config.escapeNonAscii(); + allowUnpairedSurrogates = config.allowUnpairedSurrogates(); + } + + protected static ForyJsonException unpairedSurrogate(char ch) { + return new ForyJsonException( + Character.isHighSurrogate(ch) + ? "Unpaired high surrogate in string" + : "Unpaired low surrogate in string"); } /** diff --git a/java/fory-json/src/main/java/org/apache/fory/json/writer/StringJsonWriter.java b/java/fory-json/src/main/java/org/apache/fory/json/writer/StringJsonWriter.java index f65eb249ee..7755d6aba0 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/writer/StringJsonWriter.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/writer/StringJsonWriter.java @@ -132,6 +132,9 @@ public final class StringJsonWriter extends JsonWriter implements Appendable { private byte coder; private byte nextCoder; private boolean latin1Output; + // UTF16 String values clear latin1Output before copying because their non-Latin1 char is + // normally written raw. An escaped unpaired surrogate can be that only char, so toJson rechecks. + private boolean unpairedSurrogateEscaped; private int position; public StringJsonWriter(JsonConfig config, JsonTypeResolver typeResolver) { @@ -157,6 +160,7 @@ public void reset() { } coder = nextCoder; latin1Output = coder == UTF16; + unpairedSurrogateEscaped = false; position = 0; } @@ -184,7 +188,8 @@ public String toJson() { // exposed. byte resultCoder = coder; byte[] bytes; - if (coder == UTF16 && latin1Output) { + if (coder == UTF16 + && (latin1Output || unpairedSurrogateEscaped && fitsLatin1(buffer, position))) { bytes = compressUtf16ToLatin1(buffer, position); resultCoder = LATIN1; } else { @@ -433,11 +438,16 @@ public void writeBigDecimal(BigDecimal value) { @Override public void writeChar(char value) { - if (Character.isSurrogate(value)) { + boolean surrogate = Character.isSurrogate(value); + if (surrogate && !allowUnpairedSurrogates) { throw new ForyJsonException("JSON char cannot be a surrogate: " + Integer.toHexString(value)); } writeByteRaw((byte) '"'); - writeEscapedChar(value); + if (surrogate) { + writeUnpairedSurrogate(value); + } else { + writeEscapedChar(value); + } writeByteRaw((byte) '"'); } @@ -1954,14 +1964,12 @@ private void writeStringSlow(String value, int index, int length) { continue; } ch = value.charAt(i++); - if (Character.isHighSurrogate(ch)) { - if (i >= length) { - throw new ForyJsonException("Unpaired high surrogate in string"); - } + if (!Character.isSurrogate(ch)) { + writeEscapedChar(ch); + } else if (Character.isHighSurrogate(ch) + && i < length + && Character.isLowSurrogate(value.charAt(i))) { char low = value.charAt(i++); - if (!Character.isLowSurrogate(low)) { - throw new ForyJsonException("Unpaired high surrogate in string"); - } if (escapeNonAscii) { writeUnicodeEscape(ch); writeUnicodeEscape(low); @@ -1969,10 +1977,8 @@ private void writeStringSlow(String value, int index, int length) { writeCharRaw(ch); writeCharRaw(low); } - } else if (Character.isLowSurrogate(ch)) { - throw new ForyJsonException("Unpaired low surrogate in string"); } else { - writeEscapedChar(ch); + writeUnpairedSurrogate(ch); } } writeByteRaw((byte) '"'); @@ -2020,14 +2026,12 @@ private void writeStringSlow(CharSequence value, int index, int length) { continue; } ch = value.charAt(i++); - if (Character.isHighSurrogate(ch)) { - if (i >= length) { - throw new ForyJsonException("Unpaired high surrogate in string"); - } + if (!Character.isSurrogate(ch)) { + writeEscapedChar(ch); + } else if (Character.isHighSurrogate(ch) + && i < length + && Character.isLowSurrogate(value.charAt(i))) { char low = value.charAt(i++); - if (!Character.isLowSurrogate(low)) { - throw new ForyJsonException("Unpaired high surrogate in string"); - } if (escapeNonAscii) { writeUnicodeEscape(ch); writeUnicodeEscape(low); @@ -2035,10 +2039,8 @@ private void writeStringSlow(CharSequence value, int index, int length) { writeCharRaw(ch); writeCharRaw(low); } - } else if (Character.isLowSurrogate(ch)) { - throw new ForyJsonException("Unpaired low surrogate in string"); } else { - writeEscapedChar(ch); + writeUnpairedSurrogate(ch); } } writeByteRaw((byte) '"'); @@ -2140,17 +2142,18 @@ private void writeEscapedUtf16(byte[] value) { i += 2; if (ch > 0x7f) { if (Character.isSurrogate(ch)) { - if (!Character.isHighSurrogate(ch) || i == length) { - throw new ForyJsonException("Unpaired surrogate in string"); + if (Character.isHighSurrogate(ch) + && i < length + && Character.isLowSurrogate(StringSerializer.getBytesChar(value, i))) { + LittleEndian.putInt64(bytes, pos, escapes[ch]); + pos += 6; + ch = StringSerializer.getBytesChar(value, i); + i += 2; + } else if (allowUnpairedSurrogates) { + unpairedSurrogateEscaped = true; + } else { + throw unpairedSurrogate(ch); } - char low = StringSerializer.getBytesChar(value, i); - i += 2; - if (!Character.isLowSurrogate(low)) { - throw new ForyJsonException("Unpaired high surrogate in string"); - } - LittleEndian.putInt64(bytes, pos, escapes[ch]); - pos += 6; - ch = low; } LittleEndian.putInt64(bytes, pos, escapes[ch]); pos += 6; @@ -2424,24 +2427,20 @@ private void writeStringUtf16Slow(String value, int index, int length) { continue; } ch = value.charAt(i++); - if (Character.isHighSurrogate(ch)) { - if (i >= length) { - throw new ForyJsonException("Unpaired high surrogate in string"); - } + if (!Character.isSurrogate(ch)) { + writeEscapedChar(ch); + } else if (Character.isHighSurrogate(ch) + && i < length + && Character.isLowSurrogate(value.charAt(i))) { char low = value.charAt(i++); - if (!Character.isLowSurrogate(low)) { - throw new ForyJsonException("Unpaired high surrogate in string"); - } latin1Output = false; if (position + 4 > buffer.length) { grow(4); } writeUtf16CharNoEnsure(ch); writeUtf16CharNoEnsure(low); - } else if (Character.isLowSurrogate(ch)) { - throw new ForyJsonException("Unpaired low surrogate in string"); } else { - writeEscapedChar(ch); + writeUnpairedSurrogate(ch); } } writeByteRaw((byte) '"'); @@ -2475,29 +2474,33 @@ private void writeStringUtf16Slow(CharSequence value, int index, int length) { continue; } ch = value.charAt(i++); - if (Character.isHighSurrogate(ch)) { - if (i >= length) { - throw new ForyJsonException("Unpaired high surrogate in string"); - } + if (!Character.isSurrogate(ch)) { + writeEscapedChar(ch); + } else if (Character.isHighSurrogate(ch) + && i < length + && Character.isLowSurrogate(value.charAt(i))) { char low = value.charAt(i++); - if (!Character.isLowSurrogate(low)) { - throw new ForyJsonException("Unpaired high surrogate in string"); - } latin1Output = false; if (position + 4 > buffer.length) { grow(4); } writeUtf16CharNoEnsure(ch); writeUtf16CharNoEnsure(low); - } else if (Character.isLowSurrogate(ch)) { - throw new ForyJsonException("Unpaired low surrogate in string"); } else { - writeEscapedChar(ch); + writeUnpairedSurrogate(ch); } } writeByteRaw((byte) '"'); } + private void writeUnpairedSurrogate(char ch) { + if (!allowUnpairedSurrogates) { + throw unpairedSurrogate(ch); + } + unpairedSurrogateEscaped = true; + writeUnicodeEscape(ch); + } + private void writeUnicodeEscape(char ch) { if (coder == UTF16) { if (position + 12 > buffer.length) { @@ -3113,6 +3116,15 @@ private static long spreadLatin1ToUtf16(long value) { return (value | (value << 8)) & UTF16_BYTE_MASK; } + private static boolean fitsLatin1(byte[] source, int length) { + for (int i = LITTLE_ENDIAN ? 1 : 0; i < length; i += 2) { + if (source[i] != 0) { + return false; + } + } + return true; + } + private static byte[] compressUtf16ToLatin1(byte[] source, int length) { int latin1Length = length >>> 1; byte[] target = new byte[latin1Length]; diff --git a/java/fory-json/src/main/java/org/apache/fory/json/writer/Utf8JsonWriter.java b/java/fory-json/src/main/java/org/apache/fory/json/writer/Utf8JsonWriter.java index 1b87eba0c1..435f5c6adb 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/writer/Utf8JsonWriter.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/writer/Utf8JsonWriter.java @@ -421,11 +421,16 @@ public void writeChar(char value) { position = offset + 3; return; } - if (Character.isSurrogate(value)) { + boolean surrogate = Character.isSurrogate(value); + if (surrogate && !allowUnpairedSurrogates) { throw new ForyJsonException("JSON char cannot be a surrogate: " + Integer.toHexString(value)); } writeByteRaw((byte) '"'); - writeEscapedChar(value); + if (surrogate) { + writeUnicodeEscape(value); + } else { + writeEscapedChar(value); + } writeByteRaw((byte) '"'); } @@ -2422,17 +2427,16 @@ private void writeEscapedUtf16(byte[] value) { i += 2; if (ch > 0x7f) { if (Character.isSurrogate(ch)) { - if (!Character.isHighSurrogate(ch) || i == length) { - throw new ForyJsonException("Unpaired surrogate in string"); + if (Character.isHighSurrogate(ch) + && i < length + && Character.isLowSurrogate(StringSerializer.getBytesChar(value, i))) { + LittleEndian.putInt64(bytes, pos, escapes[ch]); + pos += 6; + ch = StringSerializer.getBytesChar(value, i); + i += 2; + } else if (!allowUnpairedSurrogates) { + throw unpairedSurrogate(ch); } - char low = StringSerializer.getBytesChar(value, i); - i += 2; - if (!Character.isLowSurrogate(low)) { - throw new ForyJsonException("Unpaired high surrogate in string"); - } - LittleEndian.putInt64(bytes, pos, escapes[ch]); - pos += 6; - ch = low; } LittleEndian.putInt64(bytes, pos, escapes[ch]); pos += 6; @@ -2560,24 +2564,20 @@ private void writeStringSlow(String value, int index, int length) { continue; } ch = value.charAt(i++); - if (Character.isHighSurrogate(ch)) { - if (i >= length) { - throw new ForyJsonException("Unpaired high surrogate in string"); - } + if (!Character.isSurrogate(ch)) { + writeEscapedChar(ch); + } else if (Character.isHighSurrogate(ch) + && i < length + && Character.isLowSurrogate(value.charAt(i))) { char low = value.charAt(i++); - if (!Character.isLowSurrogate(low)) { - throw new ForyJsonException("Unpaired high surrogate in string"); - } if (escapeNonAscii) { writeUnicodeEscape(ch); writeUnicodeEscape(low); } else { writeCodePoint(Character.toCodePoint(ch, low)); } - } else if (Character.isLowSurrogate(ch)) { - throw new ForyJsonException("Unpaired low surrogate in string"); } else { - writeEscapedChar(ch); + writeUnpairedSurrogate(ch); } } writeByteRaw((byte) '"'); @@ -2604,24 +2604,20 @@ private void writeStringSlow(CharSequence value, int index, int length) { continue; } ch = value.charAt(i++); - if (Character.isHighSurrogate(ch)) { - if (i >= length) { - throw new ForyJsonException("Unpaired high surrogate in string"); - } + if (!Character.isSurrogate(ch)) { + writeEscapedChar(ch); + } else if (Character.isHighSurrogate(ch) + && i < length + && Character.isLowSurrogate(value.charAt(i))) { char low = value.charAt(i++); - if (!Character.isLowSurrogate(low)) { - throw new ForyJsonException("Unpaired high surrogate in string"); - } if (escapeNonAscii) { writeUnicodeEscape(ch); writeUnicodeEscape(low); } else { writeCodePoint(Character.toCodePoint(ch, low)); } - } else if (Character.isLowSurrogate(ch)) { - throw new ForyJsonException("Unpaired low surrogate in string"); } else { - writeEscapedChar(ch); + writeUnpairedSurrogate(ch); } } writeByteRaw((byte) '"'); @@ -2665,6 +2661,13 @@ private void writeCodePoint(int codePoint) { position = pos + 4; } + private void writeUnpairedSurrogate(char ch) { + if (!allowUnpairedSurrogates) { + throw unpairedSurrogate(ch); + } + writeUnicodeEscape(ch); + } + private void writeUnicodeEscape(char ch) { int pos = position; if (pos + 8 > buffer.length) { diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonAsyncCompilationTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonAsyncCompilationTest.java index 7f38158395..669df46c74 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonAsyncCompilationTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonAsyncCompilationTest.java @@ -1452,6 +1452,7 @@ private static ControlledJson controlledJson( onContentNullRead, false, false, + false, failOnMissingRequiredProperties, false, JsonByteArray.Format.BASE64, diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonStringTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonStringTest.java index 790dee254b..9827c88b0c 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonStringTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonStringTest.java @@ -41,11 +41,13 @@ import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.UUID; import org.apache.fory.json.annotation.JsonAnyGetter; import org.apache.fory.json.annotation.JsonMixin; import org.apache.fory.json.annotation.JsonProperty; import org.apache.fory.json.annotation.JsonPropertyOrder; import org.apache.fory.json.annotation.JsonRawValue; +import org.apache.fory.json.annotation.JsonSubTypes; import org.apache.fory.json.annotation.JsonUnwrapped; import org.apache.fory.json.codec.AbstractJsonValueCodec; import org.apache.fory.json.codec.JsonValueCodec; @@ -1447,6 +1449,225 @@ public void rejectInvalidSurrogates() { () -> json.fromJson("\"" + Character.toString('\uD800') + "\"", String.class)); } + @Test(dataProvider = "enableCodegen") + public void writeUnpairedSurrogateField(boolean codegen) { + String plain = repeat('a', 40); + String[] values = { + "\uD800", + "\uDC00", + "a\uD800b", + "\uDC00\uD800", + "\uD83D\uDE00\uD800", + "\u4E2D\uDC00", + "x\n" + plain + "\uD800" + plain, + plain + "\uDBFF", + "\uD800" + plain + "\u4E2D" + }; + for (boolean escapeNonAscii : new boolean[] {false, true}) { + ForyJson json = + newJsonBuilder(codegen) + .allowUnpairedSurrogates(true) + .escapeNonAscii(escapeNonAscii) + .build(); + for (String value : values) { + PublicFields fields = new PublicFields(); + fields.name = value; + String expected = + "{\"active\":true,\"id\":7,\"name\":" + tolerantEscape(value, escapeNonAscii) + "}"; + assertEquals(json.toJson(fields), expected, value); + assertEquals(new String(json.toJsonBytes(fields), StandardCharsets.UTF_8), expected, value); + assertEquals(json.fromJson(expected, PublicFields.class).name, value); + assertEquals(json.fromJson(json.toJsonBytes(fields), PublicFields.class).name, value); + assertEquals(json.fromJson(json.toPrettyJson(fields), PublicFields.class).name, value); + } + CharValue charValue = new CharValue(); + charValue.value = '\uDC00'; + assertEquals(json.toJson(charValue), "{\"value\":\"\\udc00\"}"); + assertEquals( + new String(json.toJsonBytes(charValue), StandardCharsets.UTF_8), + "{\"value\":\"\\udc00\"}"); + assertEquals(json.fromJson("{\"value\":\"\\udc00\"}", CharValue.class).value, '\uDC00'); + } + } + + /** Every writer path escapes an unpaired surrogate, for String and CharSequence values. */ + @Test + public void writeUnpairedSurrogates() { + String plain = repeat('a', 24); + for (boolean escapeNonAscii : new boolean[] {false, true}) { + JsonConfig config = + newJsonBuilder() + .allowUnpairedSurrogates(true) + .escapeNonAscii(escapeNonAscii) + .build() + .config(); + for (String value : + new String[] { + "\uD83D", + "\uDE00", + "\uDE00\uD83D", + "x\n" + plain + "\uD83D" + plain, + "x\n" + plain + "\uDE00" + plain, + "x\n" + plain + "\uD83D", + "x\n\u4E2D" + plain + "\uD83D" + plain, + "\u4E2D\u4E2D\u4E2D\u4E2D\uD83D\u4E2D\u4E2D\u4E2D\u4E2D", + "\uD83D\uDE00\uDE00\uD83D\uDE00" + }) { + String expected = tolerantEscape(value, escapeNonAscii); + for (CharSequence input : new CharSequence[] {value, new StringBuilder(value)}) { + Utf8JsonWriter utf8 = + new Utf8JsonWriter(config, newUtf8Writer().typeResolver(), new byte[1]); + utf8.writeString(input); + assertEquals(new String(utf8.toJsonBytes(), StandardCharsets.UTF_8), expected, value); + StringJsonWriter latin1 = + new StringJsonWriter(config, newStringWriter().typeResolver(), new byte[1]); + latin1.writeString(input); + assertEquals(latin1.toJson(), expected, value); + StringJsonWriter utf16 = + new StringJsonWriter(config, newStringWriter().typeResolver(), new byte[1]); + utf16.writeRawValue("\u4E2D"); + utf16.writeString(input); + assertEquals(utf16.toJson(), "\u4E2D" + expected, value); + } + } + } + } + + @Test + public void readUnpairedSurrogates() { + ForyJson json = newJsonBuilder().allowUnpairedSurrogates(true).build(); + String plain = repeat('a', 24); + // Escapes decode independently, so a valid escaped pair still decodes to the same pair. + String[][] escaped = { + {"\\uD800", "\uD800"}, + {"\\uDC00", "\uDC00"}, + {"\\uD800\\u0041", "\uD800A"}, + {"\\uD800x", "\uD800x"}, + {"\\uDC00\\uD800", "\uDC00\uD800"}, + {"\\uD834\\uDD1E", "\uD834\uDD1E"}, + {"\\n\\uD800", "\n\uD800"}, + {"\\u00e9\\uDBFF", "\u00e9\uDBFF"}, + {plain + "\\uDFFF" + plain, plain + "\uDFFF" + plain} + }; + for (String[] value : escaped) { + for (String prefix : new String[] {"", "\u4E2D"}) { + String text = "\"" + prefix + value[0] + "\""; + assertEquals(json.fromJson(text, String.class), prefix + value[1], text); + assertEquals(readUtf8String(json, text), prefix + value[1], text); + } + } + // Raw unpaired surrogates can occur only in String input. + String[][] raw = { + {"\uD800", "\uD800"}, + {"\uDC00", "\uDC00"}, + {"a\uD800b", "a\uD800b"}, + {"\uDC00\uD800", "\uDC00\uD800"}, + {plain + "\uD800" + plain, plain + "\uD800" + plain}, + {plain + "\uDC00", plain + "\uDC00"}, + {"\\n\uD800", "\n\uD800"}, + {"\\u00e9\uDC00", "\u00e9\uDC00"}, + {"\\u4e2d\uDC00x", "\u4E2D\uDC00x"} + }; + for (String[] value : raw) { + String text = "\"" + value[0] + "\""; + assertEquals(json.fromJson(text, String.class), value[1], text); + } + // Byte input must stay valid UTF-8, which has no encoding for a surrogate. + byte[] encodedSurrogate = {'"', (byte) 0xED, (byte) 0xA0, (byte) 0x80, '"'}; + assertThrows(ForyJsonException.class, () -> json.fromJson(encodedSurrogate, String.class)); + for (String text : new String[] {"\"\\uD800abcdef\"", "\"\u4E2D\\uD800abcdef\""}) { + assertThrows(ForyJsonException.class, () -> json.fromJson(text, UUID.class)); + assertThrows( + ForyJsonException.class, + () -> json.fromJson(text.getBytes(StandardCharsets.UTF_8), UUID.class)); + } + } + + @Test(dataProvider = "enableCodegen") + public void readUnpairedSurrogateNames(boolean codegen) { + ForyJson tolerant = newJsonBuilder(codegen).allowUnpairedSurrogates(true).build(); + for (String prefix : new String[] {"", "\u4E2D"}) { + String text = + "{\"" + + prefix + + "\\uD800\":\"\\uDC00\",\"id\":3,\"\\uDC00" + + prefix + + "\":[\"\\uD800\"],\"name\":\"\\uDBFF\"}"; + for (Object input : new Object[] {text, text.getBytes(StandardCharsets.UTF_8)}) { + PublicFields fields = read(tolerant, input, PublicFields.class); + assertEquals(fields.id, 3); + assertEquals(fields.name, "\uDBFF"); + assertEquals( + read(tolerant, input, new TypeRef>() {}).get(prefix + "\uD800"), + "\uDC00"); + } + String rawText = "{\"" + prefix + "\uD800\":1,\"id\":4,\"\uDC00\":\"\uD800\"}"; + assertEquals(tolerant.fromJson(rawText, PublicFields.class).id, 4); + String shapeText = + "{\"" + prefix + "\\uD800\":\"\\uDC00\",\"kind\":\"circle\",\"label\":\"\\uDBFF\"}"; + for (Object input : new Object[] {shapeText, shapeText.getBytes(StandardCharsets.UTF_8)}) { + SurrogateShape shape = read(tolerant, input, SurrogateShape.class); + assertEquals(((SurrogateCircle) shape).label, "\uDBFF"); + } + SurrogateShape rawShape = + tolerant.fromJson( + "{\"" + prefix + "\uDC00\":1,\"kind\":\"circle\",\"label\":\"\uD800\"}", + SurrogateShape.class); + assertEquals(((SurrogateCircle) rawShape).label, "\uD800"); + ForyJson strict = newJson(codegen); + assertThrows(ForyJsonException.class, () -> strict.fromJson(text, PublicFields.class)); + assertThrows(ForyJsonException.class, () -> strict.fromJson(shapeText, SurrogateShape.class)); + } + Map map = Collections.singletonMap("\uD800", "\uDC00"); + assertEquals(tolerant.toJson(map), "{\"\\ud800\":\"\\udc00\"}"); + assertEquals( + new String(tolerant.toJsonBytes(map), StandardCharsets.UTF_8), "{\"\\ud800\":\"\\udc00\"}"); + } + + @JsonSubTypes( + property = "kind", + value = {@JsonSubTypes.Type(value = SurrogateCircle.class, name = "circle")}) + public interface SurrogateShape {} + + public static final class SurrogateCircle implements SurrogateShape { + public String label; + } + + private static T read(ForyJson json, Object input, Class type) { + return input instanceof String + ? json.fromJson((String) input, type) + : json.fromJson((byte[]) input, type); + } + + private static T read(ForyJson json, Object input, TypeRef type) { + return input instanceof String + ? json.fromJson((String) input, type) + : json.fromJson((byte[]) input, type); + } + + /** Expected tolerant output: an unpaired surrogate always becomes a lowercase escape. */ + private static String tolerantEscape(String value, boolean escapeNonAscii) { + StringBuilder builder = new StringBuilder("\""); + for (int i = 0; i < value.length(); i++) { + char ch = value.charAt(i); + boolean paired = + Character.isHighSurrogate(ch) + && i + 1 < value.length() + && Character.isLowSurrogate(value.charAt(i + 1)) + || Character.isLowSurrogate(ch) + && i > 0 + && Character.isHighSurrogate(value.charAt(i - 1)); + if (ch == '\n') { + builder.append("\\n"); + } else if (Character.isSurrogate(ch) && !paired || escapeNonAscii && ch > 0x7f) { + builder.append(String.format("\\u%04x", (int) ch)); + } else { + builder.append(ch); + } + } + return builder.append('"').toString(); + } + private static byte[] sharedBuffer(ForyJson json) { return (byte[]) currentStateField(json, "buffer"); } diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonTestSupport.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonTestSupport.java index 8887d81c06..bd1dcb7cc2 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonTestSupport.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonTestSupport.java @@ -52,6 +52,7 @@ final class JsonTestSupport { false, false, false, + false, JsonByteArray.Format.BASE64, false, false, From f8165d060cdfd2f701ed84ec7c09a9aa7561565b Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 17 Nov 2026 15:45:58 +0100 Subject: [PATCH 2/2] docs(java): limit unpaired surrogate option to string data Names declared in code are escaped and validated when type metadata is built, so they keep strict validation. State that in the builder and JsonConfig Javadoc and the JSON guide. Co-Authored-By: Claude Opus 5.5 --- docs/json/object-mapping.md | 12 +++++++----- .../java/org/apache/fory/json/ForyJsonBuilder.java | 7 ++++--- .../main/java/org/apache/fory/json/JsonConfig.java | 5 +++-- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/docs/json/object-mapping.md b/docs/json/object-mapping.md index 0878684500..28304dc24f 100644 --- a/docs/json/object-mapping.md +++ b/docs/json/object-mapping.md @@ -310,7 +310,7 @@ overrides `JsonInclude` on the class, which overrides the builder default. See | `writeNullFields(boolean)` | `false` | Select `ALWAYS` when true or `NON_NULL` when false | | `writeLongAsString(boolean)` | `false` | Write built-in 64-bit integer values as decimal strings | | `escapeNonAscii(boolean)` | `false` | Escape non-ASCII characters in generated JSON strings and names | -| `allowUnpairedSurrogates(boolean)` | `false` | Read and write unpaired UTF-16 surrogates in strings and names | +| `allowUnpairedSurrogates(boolean)` | `false` | Read and write unpaired UTF-16 surrogates in string data | | `byteArrayFormat(JsonByteArray.Format)` | `BASE64` | Default byte-array representation for reading and writing | | `withCodegen(boolean)` | `true` | Enable generated object codecs | | `withAsyncCompilation(boolean)` | `true` | Compile generated codecs asynchronously | @@ -413,10 +413,12 @@ String text = json.toJson(value); // "a\ud83d" When enabled, reading decodes each `\uXXXX` escape on its own, so an escaped surrogate without its partner becomes that single `char`. A raw unpaired surrogate in `String` input is kept as is. Byte and stream input must still be valid UTF-8, which has no encoding for a surrogate. Writing emits -an unpaired surrogate in string and `char` values, property names, and map keys as a lowercase -`\uXXXX` escape through all String, UTF-8, stream, and pretty write APIs, so the output is valid -UTF-8 and reads back to the same value with the option enabled. Surrogate pairs are read and -written as before, and raw JSON values supplied by the caller are still validated. +an unpaired surrogate in string and `char` values and map keys as a lowercase `\uXXXX` escape +through all String, UTF-8, stream, and pretty write APIs, so the output is valid UTF-8 and reads +back to the same value with the option enabled. Property names read from input may contain unpaired +surrogates; such a name matches no declared property. Surrogate pairs are read and written as +before. Raw JSON values supplied by the caller and names declared in code, such as `@JsonProperty` +and subtype names, are still validated. The setting defaults to `false` and is fixed for each built instance. diff --git a/java/fory-json/src/main/java/org/apache/fory/json/ForyJsonBuilder.java b/java/fory-json/src/main/java/org/apache/fory/json/ForyJsonBuilder.java index 1f46fa28a9..3f43e93377 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/ForyJsonBuilder.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/ForyJsonBuilder.java @@ -197,9 +197,10 @@ public ForyJsonBuilder escapeNonAscii(boolean escapeNonAscii) { * surrogate without its partner becomes that single {@code char} in the decoded value, and a raw * unpaired surrogate in {@code String} input is kept as is. Byte input must still be valid UTF-8, * which cannot encode a surrogate. Writing emits an unpaired surrogate in a {@code String} or - * {@code char} value as a lowercase \uXXXX escape, so String, UTF-8, stream, and - * pretty output all read back to the same value. Paired surrogates are read and written as - * before, and raw JSON supplied by the caller is still validated. + * {@code char} value or map key as a lowercase \uXXXX escape, so String, UTF-8, + * stream, and pretty output all read back to the same value. Paired surrogates are read and + * written as before. Raw JSON supplied by the caller and names declared in code, such as {@code + * JsonProperty} and subtype names, are still validated. * *

The setting is fixed when {@link #build()} is called. */ diff --git a/java/fory-json/src/main/java/org/apache/fory/json/JsonConfig.java b/java/fory-json/src/main/java/org/apache/fory/json/JsonConfig.java index fe9879ffee..82ddf382f5 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/JsonConfig.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/JsonConfig.java @@ -151,8 +151,9 @@ public boolean escapeNonAscii() { } /** - * Returns whether JSON strings and names may contain unpaired UTF-16 surrogates. Reads decode - * each escape independently, and writes escape an unpaired surrogate. + * Returns whether JSON string data may contain unpaired UTF-16 surrogates. Reads decode each + * escape independently, and writes escape an unpaired surrogate in values and map keys. Names + * declared in code are still validated. */ public boolean allowUnpairedSurrogates() { return allowUnpairedSurrogates;