Jackson DefaultPrettyPrinter format json as
{
"field" : [ 1, 2 ]
}
How to configure it to format json without space before colon and with each element of array starting from a new line as GSON does?
{
"field": [
1,
2
]
}
Jackson DefaultPrettyPrinter format json as
{
"field" : [ 1, 2 ]
}
How to configure it to format json without space before colon and with each element of array starting from a new line as GSON does?
{
"field": [
1,
2
]
}
I implemented PrettyPrinter which formats json exactly like GSON
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.util.DefaultIndenter;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.core.util.Separators;
import java.io.IOException;
public class MyPrettyPrinter extends DefaultPrettyPrinter {
public MyPrettyPrinter() {
_arrayIndenter = DefaultIndenter.SYSTEM_LINEFEED_INSTANCE;
_objectIndenter = DefaultIndenter.SYSTEM_LINEFEED_INSTANCE;
}
public MyPrettyPrinter(DefaultPrettyPrinter base) {
super(base);
}
@Override
public MyPrettyPrinter createInstance() {
if (getClass() != MyPrettyPrinter.class) {
throw new IllegalStateException("Failed `createInstance()`: " + getClass().getName()
+ " does not override method; it has to");
}
return new MyPrettyPrinter(this);
}
@Override
public MyPrettyPrinter withSeparators(Separators separators) {
this._separators = separators;
this._objectFieldValueSeparatorWithSpaces = separators.getObjectFieldValueSeparator() + " ";
return this;
}
@Override
public void writeEndArray(JsonGenerator g, int nrOfValues) throws IOException {
if (!_arrayIndenter.isInline()) {
--_nesting;
}
if (nrOfValues > 0) {
_arrayIndenter.writeIndentation(g, _nesting);
}
g.writeRaw(']');
}
@Override
public void writeEndObject(JsonGenerator g, int nrOfEntries) throws IOException {
if (!_objectIndenter.isInline()) {
--_nesting;
}
if (nrOfEntries > 0) {
_objectIndenter.writeIndentation(g, _nesting);
}
g.writeRaw('}');
}
}
Overriding withSeparators
is needed to remove space before colon. Overriding writeEndArray
and writeEndObject
is for removing space in empty array and empty object []
{}
.
The dupe I pointed has a bit older information. I made it by configuring DefaultPrettyPrinter
:
ObjectMapper om = new ObjectMapper();
DefaultPrettyPrinter dpp = new DefaultPrettyPrinter();
dpp.indentArraysWith(new DefaultIndenter(" ", "\n"));
om.setDefaultPrettyPrinter(dpp);
You have to configure the writer eventually,
ObjectMapper mapper = new ObjectMapper();
String String = "{\"field\" : [ 1, 2 ]}";
Object obj = mapper.readValue(String, Object.class);
DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
prettyPrinter.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);
System.out.println(mapper.writer(prettyPrinter).writeValueAsString(obj));
Output
{
"field" : [
1,
2
]
}