Closed sunmingtao closed 2 years ago
Turns out the ByteArrayOutputStream
cannot be put in the try block. And it's OK to put it outside the try block without calling close() method on it.
Correct code:
final JsonFactory jf = new JsonFactory();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (final JsonGenerator jg = jf.createGenerator(baos, JsonEncoding.UTF8)) {
// Write header
jg.writeStartObject();
jg.writeStringField("query", ocrSearch.getRawQueryStr());
jg.writeArrayFieldStart("matches");
final List<HighlightSnippet> snippets = getSnippets(10000L);
snippets.forEach(s -> s.write(jg));
// Write footer
jg.writeEndArray();
jg.writeEndObject();
}
String result = baos.toString(StandardCharsets.UTF_8);
Inspect the
result
object, and find the value is not well formatted json string. e.g.{"name":"abc", "age":