Skip to content

Commit c205c7d

Browse files
alexcheng1982markpollack
authored andcommitted
Fix interleaved output in JsonReader's parseJsonNode method
Replace parallelStream with stream to prevent thread-unsafe appends to the shared StringBuilder. This fixes the issue of intermingled key-value pairs in the generated Document content. Also, replace StringBuffer with StringBuilder for better performance in single-threaded context. The change ensures correct ordering of extracted JSON keys and their values in the resulting Document, improving the reliability and readability of the parsed output.
1 parent 1673907 commit c205c7d

File tree

1 file changed

+6
-6
lines changed

1 file changed

+6
-6
lines changed

spring-ai-core/src/main/java/org/springframework/ai/reader/JsonReader.java

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,19 +42,19 @@
4242
*/
4343
public class JsonReader implements DocumentReader {
4444

45-
private Resource resource;
45+
private final Resource resource;
4646

47-
private JsonMetadataGenerator jsonMetadataGenerator;
47+
private final JsonMetadataGenerator jsonMetadataGenerator;
4848

4949
private final ObjectMapper objectMapper = new ObjectMapper();
5050

5151
/**
5252
* The key from the JSON that we will use as the text to parse into the Document text
5353
*/
54-
private List<String> jsonKeysToUse;
54+
private final List<String> jsonKeysToUse;
5555

5656
public JsonReader(Resource resource) {
57-
this(resource, new ArrayList<>().toArray(new String[0]));
57+
this(resource, new String[0]);
5858
}
5959

6060
public JsonReader(Resource resource, String... jsonKeysToUse) {
@@ -92,9 +92,9 @@ public List<Document> get() {
9292
private Document parseJsonNode(JsonNode jsonNode, ObjectMapper objectMapper) {
9393
Map<String, Object> item = objectMapper.convertValue(jsonNode, new TypeReference<Map<String, Object>>() {
9494
});
95-
StringBuffer sb = new StringBuffer();
95+
var sb = new StringBuilder();
9696

97-
jsonKeysToUse.parallelStream().filter(item::containsKey).forEach(key -> {
97+
jsonKeysToUse.stream().filter(item::containsKey).forEach(key -> {
9898
sb.append(key).append(": ").append(item.get(key)).append(System.lineSeparator());
9999
});
100100

0 commit comments

Comments
 (0)