Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 31 additions & 2 deletions docs/json/object-mapping.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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 |
Expand Down Expand Up @@ -385,14 +386,42 @@ 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 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.

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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -188,6 +189,26 @@ 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.
*
* <p>When enabled, reading decodes each <code>&#92;uXXXX</code> 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 or map key as a lowercase <code>&#92;uXXXX</code> 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.
*
* <p>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.
*
Expand Down Expand Up @@ -458,6 +479,7 @@ JsonConfig buildConfig() {
onContentNullRead,
writeLongAsString,
escapeNonAscii,
allowUnpairedSurrogates,
failOnMissingRequiredProperties,
failOnDuplicateProperties,
byteArrayFormat,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -70,6 +71,7 @@ public final class JsonConfig {
NullHandling onContentNullRead,
boolean writeLongAsString,
boolean escapeNonAscii,
boolean allowUnpairedSurrogates,
boolean failOnMissingRequiredProperties,
boolean failOnDuplicateProperties,
JsonByteArray.Format byteArrayFormat,
Expand All @@ -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");
Expand Down Expand Up @@ -147,6 +150,15 @@ public boolean escapeNonAscii() {
return escapeNonAscii;
}

/**
* 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;
}

/** Returns whether required creator properties must appear in the input. */
public boolean failOnMissingRequiredProperties() {
return failOnMissingRequiredProperties;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
}

/**
Expand Down Expand Up @@ -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;
Expand All @@ -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) {
Expand All @@ -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");
}
Expand All @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand All @@ -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) {
Expand Down Expand Up @@ -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;
Expand All @@ -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) {
Expand Down Expand Up @@ -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;
Expand All @@ -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) {
Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading