Java MinimalPrettyPrinter-class And Method Code Example
Here is an example of how to use the MinimalPrettyPrinter class from the org.apache.commons.io package in Java:
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.apache.commons.io.output.MinimalPrettyPrinter;
import java.io.StringWriter;
public class Main {
public static void main(String[] args) throws Exception {
JsonFactory jsonFactory = new JsonFactory();
StringWriter writer = new StringWriter();
JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(writer);
MinimalPrettyPrinter prettyPrinter = new MinimalPrettyPrinter();
jsonGenerator.setPrettyPrinter(prettyPrinter);
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("name", "John");
jsonGenerator.writeNumberField("age", 30);
jsonGenerator.writeEndObject();
jsonGenerator.close();
System.out.println(writer.toString());
}
}
In this example, we create a JsonFactory, JsonGenerator and MinimalPrettyPrinter objects. We use the MinimalPrettyPrinter object to set the pretty printer for the JsonGenerator, and then write a JSON object with two fields, "name" and "age". We then close the JsonGenerator and print the resulting JSON string.
It's worth noting that this class was removed from the apache.commons.io library in version 2.6 and later versions, you can use other libraries like Jackson library's JsonGenerator to achieve similar functionality.