Skip to content
Advertisement

How to write output of JsonGenerator?

I’m attempting to write the output of data generated by JsonGenerator to console using :

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;

import java.io.IOException;
import java.io.StringWriter;

public class JsonGeneratorTest {

    public static void main(String args[]) throws IOException {

        var out = new StringWriter();

        JsonFactory factory = new JsonFactory();
        JsonGenerator generator = factory.createGenerator(out);

        generator.useDefaultPrettyPrinter();

        generator.writeStartObject();
        generator.writeStringField("name", "zhangsan");
        generator.writeNumberField("age", 18);
        generator.writeEndObject();

        System.out.println("Output : "+out.toString());

        System.out.println("generator : "+out.getBuffer().toString());

    }

}

From the Java docs – https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/io/StringWriter.html:

getBuffer
public StringBuffer getBuffer()
Return the string buffer itself.
Returns:
StringBuffer holding the current buffer value.

Shouldn’t the current value written to the Json generator be outputted when I use :

out.getBuffer().toString()

Advertisement

Answer

Issue is not closing the generator, updated code :

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import java.io.IOException;
import java.io.StringWriter;

public class JsonGeneratorTest {

    public static void main(String args[]) throws IOException {

        var out = new StringWriter();

        JsonFactory factory = new JsonFactory();
        JsonGenerator generator = factory.createGenerator(out);

        generator.useDefaultPrettyPrinter();

        generator.writeStartObject();
        generator.writeStringField("name", "zhangsan");
        generator.writeNumberField("age", 18);
        generator.writeEndObject();
        generator.close();

        generator.getCurrentValue();
        System.out.println("Output : "+out);
        System.out.println("generator : "+out.getBuffer().toString());
        System.out.println("getCurrentValue : "+generator.getCurrentValue());

    }

}

prints :

    Output : {
  "name" : "zhangsan",
  "age" : 18
}
generator : {
  "name" : "zhangsan",
  "age" : 18
}
getCurrentValue : null
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement