Skip to content

Commit 11c3b01

Browse files
authored
fix(jsonrpc): prefer a populated content key when decoding a Part (a2aproject#1061)
The discriminator scan took the first content key that was merely non-null, so a producer that emits every key of the flattened oneOf with the unset ones as "" lost its payload to whichever empty placeholder came first on the wire. The comment above it already promised "skipping null/empty values"; only null was ever skipped. This fixes a2aproject#1062
1 parent 45e5065 commit 11c3b01

2 files changed

Lines changed: 195 additions & 16 deletions

File tree

‎jsonrpc-common/src/main/java/org/a2aproject/sdk/jsonrpc/common/json/JsonUtil.java‎

Lines changed: 34 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import java.util.List;
1818
import java.util.Map;
1919
import java.util.Set;
20+
import java.util.stream.Stream;
2021

2122
import com.google.gson.Gson;
2223
import com.google.gson.GsonBuilder;
@@ -508,8 +509,8 @@ public static Map<String, Object> readMetadata(@Nullable String json) throws Jso
508509
* This adapter handles polymorphic deserialization, creating the
509510
* appropriate subclass instance (TextPart, FilePart, or DataPart) based on available fields.
510511
* <p>
511-
* The adapter uses a two-pass approach: first reads the JSON as a tree to inspect the "kind"
512-
* field, then deserializes to the appropriate concrete type.
512+
* The adapter reads the JSON as a tree so that the content key can be inspected before
513+
* deserializing to the appropriate concrete type.
513514
*
514515
* @see Part
515516
* @see TextPart
@@ -599,29 +600,23 @@ Part<?> read(JsonReader in) throws java.io.IOException {
599600
Map<String, Object> metadata = JsonUtil.readMetadata(jsonObject);
600601
Set<String> keys = jsonObject.keySet();
601602

602-
// Find the oneOf discriminator, skipping null/empty values to tolerate formats
603-
// where multiple content keys may be present with only one populated
604-
// (e.g., proto serialization with alwaysPrintFieldsWithNoPresence).
605-
// Unknown extra fields are ignored.
606-
String discriminator = keys.stream()
607-
.filter(VALID_KEYS::contains)
608-
.filter(key -> {
609-
com.google.gson.JsonElement el = jsonObject.get(key);
610-
return el != null && !el.isJsonNull();
611-
})
612-
.findFirst()
603+
// A producer that emits every content key, leaving the unset ones as "", would otherwise
604+
// have its payload discarded by whichever empty placeholder came first on the wire.
605+
// The fallback keeps a deliberately empty TextPart decodable.
606+
String discriminator = contentKeys(jsonObject).filter(key -> !isEmptyString(jsonObject.get(key))).findFirst()
607+
.or(() -> contentKeys(jsonObject).findFirst())
613608
.orElseThrow(() -> new JsonSyntaxException(format("Part must have one of: %s (found: %s)", VALID_KEYS, keys)));
614609

615610
return switch (discriminator) {
616-
case TEXT -> new TextPart(jsonObject.get(TEXT).getAsString(), metadata);
611+
case TEXT -> new TextPart(requireString(jsonObject, TEXT), metadata);
617612
case RAW -> new FilePart(new FileWithBytes(
618613
stringOrEmpty(jsonObject, MEDIA_TYPE),
619614
stringOrEmpty(jsonObject, FILENAME),
620-
jsonObject.get(RAW).getAsString()), metadata);
615+
requireString(jsonObject, RAW)), metadata);
621616
case URL -> new FilePart(new FileWithUri(
622617
stringOrEmpty(jsonObject, MEDIA_TYPE),
623618
stringOrEmpty(jsonObject, FILENAME),
624-
jsonObject.get(URL).getAsString()), metadata);
619+
requireString(jsonObject, URL)), metadata);
625620
case DATA -> {
626621
Object data = delegateGson.fromJson(jsonObject.get(DATA), Object.class);
627622
yield new DataPart(data, metadata);
@@ -630,6 +625,29 @@ Part<?> read(JsonReader in) throws java.io.IOException {
630625
};
631626
}
632627

628+
/** Returns the content keys carrying a non-null value, in document order. */
629+
private Stream<String> contentKeys(com.google.gson.JsonObject obj) {
630+
return obj.keySet().stream()
631+
.filter(VALID_KEYS::contains)
632+
.filter(key -> {
633+
JsonElement el = obj.get(key);
634+
return el != null && !el.isJsonNull();
635+
});
636+
}
637+
638+
private boolean isEmptyString(@Nullable JsonElement el) {
639+
return el != null && el.isJsonPrimitive() && el.getAsJsonPrimitive().isString() && el.getAsString().isEmpty();
640+
}
641+
642+
/** Guards {@code getAsString()}, which throws an unchecked UnsupportedOperationException on an object or array. */
643+
private String requireString(com.google.gson.JsonObject obj, String key) {
644+
JsonElement el = obj.get(key);
645+
if (el == null || !el.isJsonPrimitive()) {
646+
throw new JsonSyntaxException(format("Part '%s' must be a JSON string", key));
647+
}
648+
return el.getAsString();
649+
}
650+
633651
/** Returns the string value of the field, or an empty string if absent or null. */
634652
private String stringOrEmpty(com.google.gson.JsonObject obj, String key) {
635653
com.google.gson.JsonElement el = obj.get(key);
Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
package org.a2aproject.sdk.jsonrpc.common.json;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
5+
import static org.junit.jupiter.api.Assertions.assertThrows;
6+
7+
import java.util.Map;
8+
9+
import org.a2aproject.sdk.spec.DataPart;
10+
import org.a2aproject.sdk.spec.FilePart;
11+
import org.a2aproject.sdk.spec.FileWithBytes;
12+
import org.a2aproject.sdk.spec.FileWithUri;
13+
import org.a2aproject.sdk.spec.Part;
14+
import org.a2aproject.sdk.spec.TextPart;
15+
import org.junit.jupiter.api.Test;
16+
import org.junit.jupiter.params.ParameterizedTest;
17+
import org.junit.jupiter.params.provider.ValueSource;
18+
19+
/**
20+
* Decoding of the flat Part oneOf when a producer emits more than one content key.
21+
*/
22+
public class PartSerializationTest {
23+
24+
@Test
25+
void testPopulatedDataWinsOverEmptyTextPlaceholder() throws JsonProcessingException {
26+
String json = """
27+
{"text": "", "data": {"answer": "42"}}
28+
""";
29+
Part<?> part = JsonUtil.fromJson(json, Part.class);
30+
assertInstanceOf(DataPart.class, part);
31+
@SuppressWarnings("unchecked")
32+
Map<String, Object> data = (Map<String, Object>) ((DataPart) part).data();
33+
assertEquals("42", data.get("answer"));
34+
}
35+
36+
@Test
37+
void testDataPartDecodesRegardlessOfContentKeyOrder() throws JsonProcessingException {
38+
String json = """
39+
{"data": {"answer": "42"}, "text": ""}
40+
""";
41+
Part<?> part = JsonUtil.fromJson(json, Part.class);
42+
assertInstanceOf(DataPart.class, part);
43+
@SuppressWarnings("unchecked")
44+
Map<String, Object> data = (Map<String, Object>) ((DataPart) part).data();
45+
assertEquals("42", data.get("answer"));
46+
}
47+
48+
@Test
49+
void testPopulatedDataWinsOverAllEmptyPlaceholders() throws JsonProcessingException {
50+
String json = """
51+
{"text": "", "raw": "", "url": "", "data": {"answer": "42"}}
52+
""";
53+
Part<?> part = JsonUtil.fromJson(json, Part.class);
54+
assertInstanceOf(DataPart.class, part);
55+
@SuppressWarnings("unchecked")
56+
Map<String, Object> data = (Map<String, Object>) ((DataPart) part).data();
57+
assertEquals("42", data.get("answer"));
58+
}
59+
60+
@Test
61+
void testPopulatedUrlWinsOverEmptyTextPlaceholder() throws JsonProcessingException {
62+
String json = """
63+
{"text": "", "url": "https://example.org/report.pdf", "mediaType": "application/pdf"}
64+
""";
65+
Part<?> part = JsonUtil.fromJson(json, Part.class);
66+
assertInstanceOf(FilePart.class, part);
67+
FileWithUri file = (FileWithUri) ((FilePart) part).file();
68+
assertEquals("https://example.org/report.pdf", file.uri());
69+
assertEquals("application/pdf", file.mimeType());
70+
}
71+
72+
@Test
73+
void testPopulatedRawWinsOverEmptyTextPlaceholder() throws JsonProcessingException {
74+
String json = """
75+
{"text": "", "raw": "abc12w==", "filename": "diagram.png", "mediaType": "image/png"}
76+
""";
77+
Part<?> part = JsonUtil.fromJson(json, Part.class);
78+
assertInstanceOf(FilePart.class, part);
79+
FileWithBytes file = (FileWithBytes) ((FilePart) part).file();
80+
assertEquals("abc12w==", file.bytes());
81+
assertEquals("diagram.png", file.name());
82+
assertEquals("image/png", file.mimeType());
83+
}
84+
85+
/** Emptiness is decided on the JSON string only, so a falsy data payload still outranks a placeholder. */
86+
@ParameterizedTest
87+
@ValueSource(strings = {"0", "false", "{}", "[]"})
88+
void testFalsyDataPayloadWinsOverEmptyTextPlaceholder(String payload) throws JsonProcessingException {
89+
Part<?> part = JsonUtil.fromJson("{\"text\": \"\", \"data\": " + payload + "}", Part.class);
90+
assertInstanceOf(DataPart.class, part);
91+
}
92+
93+
@Test
94+
void testJsonNullContentKeyIsSkipped() throws JsonProcessingException {
95+
String json = """
96+
{"text": "hello", "data": null}
97+
""";
98+
Part<?> part = JsonUtil.fromJson(json, Part.class);
99+
assertInstanceOf(TextPart.class, part);
100+
assertEquals("hello", ((TextPart) part).text());
101+
}
102+
103+
@Test
104+
void testPopulatedDataWinsOverJsonNullText() throws JsonProcessingException {
105+
String json = """
106+
{"text": null, "data": {"answer": "42"}}
107+
""";
108+
Part<?> part = JsonUtil.fromJson(json, Part.class);
109+
assertInstanceOf(DataPart.class, part);
110+
@SuppressWarnings("unchecked")
111+
Map<String, Object> data = (Map<String, Object>) ((DataPart) part).data();
112+
assertEquals("42", data.get("answer"));
113+
}
114+
115+
@Test
116+
void testDeliberatelyEmptyTextPartDecodes() throws JsonProcessingException {
117+
String json = """
118+
{"text": ""}
119+
""";
120+
Part<?> part = JsonUtil.fromJson(json, Part.class);
121+
assertInstanceOf(TextPart.class, part);
122+
assertEquals("", ((TextPart) part).text());
123+
}
124+
125+
@Test
126+
void testEmptyTextPartRoundTrips() throws JsonProcessingException {
127+
String json = JsonUtil.toJson(new TextPart(""));
128+
Part<?> part = JsonUtil.fromJson(json, Part.class);
129+
assertInstanceOf(TextPart.class, part);
130+
assertEquals("", ((TextPart) part).text());
131+
}
132+
133+
@Test
134+
void testDataPartWithEmptyStringPayloadDecodes() throws JsonProcessingException {
135+
String json = """
136+
{"data": ""}
137+
""";
138+
Part<?> part = JsonUtil.fromJson(json, Part.class);
139+
assertInstanceOf(DataPart.class, part);
140+
assertEquals("", ((DataPart) part).data());
141+
}
142+
143+
/** Nothing distinguishes the intended content when every key is an empty string, so order decides. */
144+
@Test
145+
void testAllEmptyContentKeysFallBackToTheFirst() throws JsonProcessingException {
146+
String json = """
147+
{"text": "", "data": ""}
148+
""";
149+
Part<?> part = JsonUtil.fromJson(json, Part.class);
150+
assertInstanceOf(TextPart.class, part);
151+
assertEquals("", ((TextPart) part).text());
152+
}
153+
154+
@Test
155+
void testNonStringContentKeyIsRejected() {
156+
String json = """
157+
{"text": "", "raw": {"nested": 1}}
158+
""";
159+
assertThrows(JsonProcessingException.class, () -> JsonUtil.fromJson(json, Part.class));
160+
}
161+
}

0 commit comments

Comments
 (0)