To achieve format like this you need to implement your own PrettyPrinter
:
class ObjectArrayInNewLinePrettyPrinter extends DefaultPrettyPrinter {
public ObjectArrayInNewLinePrettyPrinter() {
super();
}
public ObjectArrayInNewLinePrettyPrinter(DefaultPrettyPrinter base) {
super(base);
}
@Override
public void writeStartObject(JsonGenerator g) throws IOException {
_objectIndenter.writeIndentation(g, _nesting);
super.writeStartObject(g);
}
@Override
public void writeStartArray(JsonGenerator g) throws IOException {
_arrayIndenter.writeIndentation(g, _nesting);
super.writeStartArray(g);
}
@Override
public DefaultPrettyPrinter createInstance() {
return new ObjectArrayInNewLinePrettyPrinter(this);
}
}
And you can use it as below:
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.util.DefaultIndenter;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import java.io.File;
import java.io.IOException;
public class JsonPrettyPrinterApp {
public static void main(String[] args) throws IOException {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
DefaultPrettyPrinter printer = new ObjectArrayInNewLinePrettyPrinter();
printer.indentArraysWith(new DefaultIndenter());
JsonMapper mapper = JsonMapper.builder()
.enable(SerializationFeature.INDENT_OUTPUT)
.defaultPrettyPrinter(printer)
.build();
JsonNode root = mapper.readTree(jsonFile);
mapper.writeValue(System.out, root);
}
}
above code prints:
{
"type" : "aaa",
"key" :
{
"key1" : "bbb",
"key 2" :
[
{
"value" : "xx"
},
{
"value" : "sss"
},
{
"value" : "zzz"
}
]
}
}
which prints something similar to what you want.