diff --git a/docs/json/annotations.md b/docs/json/annotations.md index 69deba4065..f34661ec83 100644 --- a/docs/json/annotations.md +++ b/docs/json/annotations.md @@ -545,11 +545,14 @@ make the enclosing output invalid or change its structure. Java null still follo normal inclusion policy and, when included, is written as JSON `null`. Reading remains ordinary String-property reading. For example, `{"body":"text"}` can populate the -field, but an object such as `{"body":{"id":1}}` cannot be read back into it. `JsonRawValue` is not -a type-use annotation and does not apply to container elements or Map values. It cannot be placed -on a setter, creator parameter, Any declaration, or the same property occurrence as `JsonCodec`. -As an occurrence-local representation, it keeps the raw String shape even when the value type has -an exact builder-registered codec. +field, but an object such as `{"body":{"id":1}}` cannot be read back into it. To capture any JSON +value as its source text, select a custom codec for the property whose read operation calls +`JsonReader.readRawValue()`; see [Reading raw values](custom-codecs.md#reading-raw-values). + +`JsonRawValue` is not a type-use annotation and does not apply to container elements or Map values. +It cannot be placed on a setter, creator parameter, Any declaration, or the same property +occurrence as `JsonCodec`. As an occurrence-local representation, it keeps the raw String shape +even when the value type has an exact builder-registered codec. `JsonRawValue` does not collect unknown sibling fields. Unknown fields are skipped unless an existing `JsonAnyProperty` or `JsonAnyGetter`/`JsonAnySetter` owner captures them. The raw-value and diff --git a/docs/json/custom-codecs.md b/docs/json/custom-codecs.md index efa517df0f..e6743d2350 100644 --- a/docs/json/custom-codecs.md +++ b/docs/json/custom-codecs.md @@ -152,6 +152,45 @@ Registering a custom codec for a `JsonSubTypes` base replaces that base's subtyp Registering one for a listed subtype is supported by the two wrapper inclusions but not by inline property inclusion. +## Reading raw values + +`JsonReader.readRawValue()` reads the next complete JSON value and returns its exact source text +without decoding it. It is the read-side counterpart of `JsonRawValue` and of the writers' +`writeRawValue(String)`, for codecs that pass a nested value to another parser or keep it opaque: + +```java +import org.apache.fory.json.codec.AbstractJsonValueCodec; +import org.apache.fory.json.reader.JsonReader; +import org.apache.fory.json.writer.JsonWriter; + +/** Accepts an object either inline or as a JSON string that contains the object text. */ +public final class ObjectTextCodec extends AbstractJsonValueCodec { + @Override + public void write(JsonWriter writer, String value) { + if (value == null) { + writer.writeNull(); + } else { + writer.writeString(value); + } + } + + @Override + public String read(JsonReader reader) { + if (reader.tryReadNullToken()) { + return null; + } + return reader.peekToken() == '"' ? reader.readString() : reader.readRawValue(); + } +} +``` + +Leading whitespace is skipped and is not part of the result. The value keeps its inner whitespace, +string quotes, and escape sequences exactly as in the input, and a JSON `null` token is returned as +the text `null`, not as Java null. The reader stops right after the value, so the enclosing +property, element, or root parse continues normally. The value is validated like `skipValue()`, +including string escapes, UTF-8 input, and the configured maximum depth counted from the current +nesting level. The returned String is a leaf value and is not charged to the graph-memory budget. + ## Custom empty values `NON_EMPTY` calls the selected codec's `isEmpty(JsonWriter writer, T value)` for non-null values 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..8d32cb2128 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 @@ -719,6 +719,28 @@ public Number readNumber() { return materializeNumber(readNumberAsString()); } + /** + * Reads the next complete JSON value and returns its exact source text without decoding it. + * + *

This is the read-side counterpart of {@code JsonRawValue}: a custom codec can capture an + * object, array, string, number, boolean, or {@code null} token as it appears in the input, for + * example to hand a nested document to another JSON parser. Leading whitespace is skipped and not + * included; whitespace inside a container, string quotes, and escape sequences are kept verbatim; + * a JSON {@code null} token is returned as the text {@code "null"}, not as Java null. The reader + * stops immediately after the value, so the caller still consumes the following comma or closing + * delimiter as usual. + * + *

The value is validated with the same rules and the same configured maximum depth as {@link + * #skipValue()}, counted from the current nesting depth. The returned String is a leaf value and + * is not charged to the graph-memory budget. + */ + public final String readRawValue() { + skipWhitespace(); + int start = position; + skipValue(); + return rawText(start, position); + } + private String readNumberToken() { int start = position; scanNumberToken(); @@ -3282,6 +3304,15 @@ private int hexValue(char ch) { protected abstract String slice(int start, int end); + /** + * Returns the source text of an already validated value span. Unlike {@link #slice(int, int)}, + * which only receives ASCII token spans, the span may contain decoded string content in the + * input's own encoding. + */ + protected String rawText(int start, int end) { + return slice(start, end); + } + private static final class NumericWorkspace { private long[] bigIntegerBuffer = new long[4]; } 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..2b416e0ed3 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 @@ -23,6 +23,7 @@ import java.lang.invoke.MethodType; import java.math.BigDecimal; import java.math.BigInteger; +import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; @@ -4342,6 +4343,12 @@ protected String slice(int start, int end) { return newLatin1String(start, end); } + @Override + protected String rawText(int start, int end) { + // String content was validated as UTF-8 while the span was skipped. + return new String(input, start, end - start, StandardCharsets.UTF_8); + } + private String newLatin1String(int start, int end) { int length = end - start; byte[] bytes = new byte[length]; diff --git a/java/fory-json/src/test/java/org/apache/fory/json/ForyJsonTokenOperationTest.java b/java/fory-json/src/test/java/org/apache/fory/json/ForyJsonTokenOperationTest.java index ad7326acda..5cd7a3e600 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/ForyJsonTokenOperationTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/ForyJsonTokenOperationTest.java @@ -31,6 +31,7 @@ import java.nio.charset.StandardCharsets; import java.util.function.Consumer; import java.util.function.Function; +import org.apache.fory.json.reader.JsonReader; import org.apache.fory.json.reader.Utf8JsonReader; import org.apache.fory.json.writer.Utf8JsonWriter; import org.testng.annotations.Test; @@ -148,6 +149,56 @@ public void readerIsBorrowedFromThePool() { json.readUtf8("false".getBytes(StandardCharsets.UTF_8), 0, 5, Utf8JsonReader::readBoolean)); } + @Test + public void readRawValueKeepsSourceText() { + String input = " [ {\"a\" : [1, 2]} ,\"x\\u0041\u00e9\", 1.5e-3, true, null,\n{} ]"; + String[] expected = {"{\"a\" : [1, 2]}", "\"x\\u0041\u00e9\"", "1.5e-3", "true", "null", "{}"}; + // Byte input: on JDK 8 a String is never byte-backed, so the String constructor rejects it. + assertRawValues( + JsonTestSupport.newLatin1Reader(input.getBytes(StandardCharsets.ISO_8859_1)), expected); + assertRawValues(JsonTestSupport.newUtf16Reader(input), expected); + assertRawValues( + JsonTestSupport.newUtf8Reader(input.getBytes(StandardCharsets.UTF_8)), expected); + + String unicode = "[\"\u4f60\u597d\",{\"k\":\"\ud83d\ude00\"}]"; + String[] unicodeValues = {"\"\u4f60\u597d\"", "{\"k\":\"\ud83d\ude00\"}"}; + assertRawValues(JsonTestSupport.newUtf16Reader(unicode), unicodeValues); + assertRawValues( + JsonTestSupport.newUtf8Reader(unicode.getBytes(StandardCharsets.UTF_8)), unicodeValues); + + byte[] root = " {\"b\":[]} ".getBytes(StandardCharsets.UTF_8); + assertEquals(json.readUtf8(root, 0, root.length, Utf8JsonReader::readRawValue), "{\"b\":[]}"); + byte[] invalid = "{\"b\":tru}".getBytes(StandardCharsets.UTF_8); + assertThrows( + ForyJsonException.class, + () -> json.readUtf8(invalid, 0, invalid.length, Utf8JsonReader::readRawValue)); + byte[] empty = " ".getBytes(StandardCharsets.UTF_8); + assertThrows( + ForyJsonException.class, + () -> json.readUtf8(empty, 0, empty.length, Utf8JsonReader::readRawValue)); + // Invalid UTF-8 inside a string fails instead of being decoded with replacement characters, + // both in the short tail scan and in the word-at-a-time scan of a longer string. + byte[] shortString = {'{', '"', 'k', '"', ':', '"', (byte) 0xC3, '"', '}'}; + String longText = "{\"k\":\"abcdefghijklmnop?qrstuvwxyz\"}"; + byte[] longString = longText.getBytes(StandardCharsets.UTF_8); + longString[longText.indexOf('?')] = (byte) 0xFF; + for (byte[] malformed : new byte[][] {shortString, longString}) { + assertThrows( + ForyJsonException.class, + () -> json.readUtf8(malformed, 0, malformed.length, Utf8JsonReader::readRawValue)); + } + } + + private static void assertRawValues(JsonReader reader, String[] expected) { + reader.expectNextToken('['); + int index = 0; + do { + assertEquals(reader.readRawValue(), expected[index++]); + } while (reader.consumeNextCommaOrEndArray()); + assertEquals(index, expected.length); + reader.finish(); + } + private static Pair readPair(Utf8JsonReader reader) { Pair pair = new Pair(); reader.expectNextToken('{'); diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonCodecAnnotationTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonCodecAnnotationTest.java index f24d3b9f9a..54cbc70ff5 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonCodecAnnotationTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonCodecAnnotationTest.java @@ -454,6 +454,47 @@ public void precedence() { assertTrue(text.contains("\"regular\":\"builder-child\"")); } + @Test + public void rawValueCodec() { + ForyJson json = newJson(); + String object = "{\"title\": \"a\\\"b\", \"n\":[1, -2.5e3,true,null],\"o\":{}}"; + String latin1 = "{\"body\": " + object + " ,\"id\":7}"; + RawBodyModel value = json.fromJson(latin1, RawBodyModel.class); + assertEquals(value.body, object); + assertEquals(value.id, 7); + assertEquals(json.toJson(value), "{\"body\":" + object + ",\"id\":7}"); + + String unicodeObject = "{\"t\":\"\u4f60\u597d \\u00e9 \ud83d\ude00\"}"; + String unicode = "{\"id\":3,\"body\":" + unicodeObject + "}"; + assertEquals(json.fromJson(unicode, RawBodyModel.class).body, unicodeObject); + RawBodyModel utf8 = json.fromJson(unicode.getBytes(StandardCharsets.UTF_8), RawBodyModel.class); + assertEquals(utf8.body, unicodeObject); + assertEquals(utf8.id, 3); + assertEquals( + new String(json.toJsonBytes(utf8), StandardCharsets.UTF_8), + "{\"body\":" + unicodeObject + ",\"id\":3}"); + + String[] scalars = {"\"text \\n \u00e9\"", "-0.5E+2", "false", "[]"}; + for (String scalar : scalars) { + String input = "{\"body\":" + scalar + ",\"id\":1}"; + assertEquals(json.fromJson(input, RawBodyModel.class).body, scalar); + assertEquals( + json.fromJson(input.getBytes(StandardCharsets.UTF_8), RawBodyModel.class).body, scalar); + } + + assertFailure(() -> json.fromJson("{\"body\":{\"a\":01},\"id\":1}", RawBodyModel.class)); + assertFailure(() -> json.fromJson("{\"body\":{\"a\":\"x},\"id\":1}", RawBodyModel.class)); + assertFailure( + () -> + json.fromJson( + "{\"body\":[1,],\"id\":1}".getBytes(StandardCharsets.UTF_8), RawBodyModel.class)); + ForyJson shallow = newJsonBuilder().maxDepth(2).build(); + assertEquals( + shallow.fromJson("{\"body\":{\"a\":1},\"id\":1}", RawBodyModel.class).body, "{\"a\":1}"); + assertFailure( + () -> shallow.fromJson("{\"body\":{\"a\":[1]},\"id\":1}", RawBodyModel.class), "max depth"); + } + @Test public void valueAndChild() { assertFailure(() -> newJson().toJson(new InvalidComposition())); @@ -915,6 +956,40 @@ private static Value readValue(JsonReader reader) { return new Value(readTagged(reader, "V")); } + public static class RawJsonCodec implements JsonValueCodec { + @Override + public void writeString(StringJsonWriter writer, String value) { + writer.writeRawValue(value); + } + + @Override + public void writeUtf8(Utf8JsonWriter writer, String value) { + writer.writeRawValue(value); + } + + @Override + public String readLatin1(Latin1JsonReader reader) { + return reader.readRawValue(); + } + + @Override + public String readUtf16(Utf16JsonReader reader) { + return reader.readRawValue(); + } + + @Override + public String readUtf8(Utf8JsonReader reader) { + return reader.readRawValue(); + } + } + + public static class RawBodyModel { + @JsonCodec(RawJsonCodec.class) + public String body; + + public int id; + } + public static class RepresentationModel { @JsonCodec(PathStringCodec.class) public String value;