sunmingtao / sample-code

3 stars 4 forks source link

JsonGenerator generates incomplete json string #312

Closed sunmingtao closed 2 years ago

sunmingtao commented 2 years ago
final JsonFactory jf = new JsonFactory();
try (
      final ByteArrayOutputStream baos = new ByteArrayOutputStream();
      final JsonGenerator jg = jf.createGenerator(baos, JsonEncoding.UTF8)) {
        jg.writeStartObject();
        jg.writeStringField("query", ocrSearch.getRawQueryStr());
        jg.writeArrayFieldStart("matches");
        final List<HighlightSnippet> snippets = getSnippets(10000L);
        snippets.forEach(s -> s.write(jg));
        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":

sunmingtao commented 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);