Reputation: 47
I'm using Jackson library for serialization. To indent the output I have the following code
ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
This results in adding spaces that I don't need. For example,
{
"id" : 2,
"name" : "theUser"
}
I want my output to be
{
"id": 2,
"name": "theUser"
}
Basically, I want space between key and : to be removed. Is there a easy way to get rid of this additional space?
Upvotes: 1
Views: 468
Reputation: 1045
Although Ivar provided the answer already in his comment, here's my implementation of it, which returns your desired result.
DefaultPrettyPrinter pp = new MyPrettyPrinter();
ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);;
try {
jsonResult = mapper.writer(pp)
.writeValueAsString(map);
}
catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
where MyPrettyPrinter is the following:
public class MyPrettyPrinter extends DefaultPrettyPrinter {
@Override
public DefaultPrettyPrinter createInstance() {
return new MyPrettyPrinter();
}
@Override
public void writeObjectFieldValueSeparator(JsonGenerator jg) throws IOException {
jg.writeRaw(": ");
}
}
Upvotes: 2