membersound
membersound

Reputation: 86727

Pretty print Jackson json without whitespaces?

I have a json string that I want to pretty print with jackson. The following works in general:

    ObjectWriter w = new ObjectMapper()
            .writer()
            .withDefaultPrettyPrinter();

    Object obj = new ObjectMapper().readValue(json, Object.class);
    System.out.println(w.writeValueAsString(obj));

Result:

{
   "myarray" : [ {
      "field" : "val"
   } ]
}

BUT: I'd like to get the output without whitespaces between parameters. Is that possible?

Desired output:

{
   "myarray":[{
      "field":"val"
   }]
}

Upvotes: 2

Views: 4336

Answers (2)

Ilya Serbis
Ilya Serbis

Reputation: 22283

If you would like to get something like this (spaces only after colons and entities of the array are separated by line breaks)

{
  "users": [
    {
      "name": "u1",
      "age": 10
    },
    {
      "name": "u2",
      "age": 20
    }
  ]
}

you should use custom PrettyPrinter implementation:

public class CustomPrettyPrinter extends DefaultPrettyPrinter {
    public CustomPrettyPrinter() {
        super._arrayIndenter = new DefaultIndenter();
        super._objectFieldValueSeparatorWithSpaces = _separators.getObjectFieldValueSeparator() + " ";
    }

    @Override
    public CustomPrettyPrinter createInstance() {
        return new CustomPrettyPrinter();
    }
}

using the following code:

ObjectWriter writer = new ObjectMapper()
        .writer()
        .with(new CustomPrettyPrinter());
String result = writer.writeValueAsString(obj);

Upvotes: 2

Ken Chan
Ken Chan

Reputation: 90447

Yes. You can customise the DefaultPrettyPrinter with the followings:

  • Use withoutSpacesInObjectEntries() to turn off spaces inside the object entries

  • Set the array indenter to DefaultPrettyPrinter.NopIndenter such that there is no spaces to separate the array value.

Code wise , it looks like :

DefaultPrettyPrinter pp = new DefaultPrettyPrinter()
            .withoutSpacesInObjectEntries()
            .withArrayIndenter(new DefaultPrettyPrinter.NopIndenter());

ObjectWriter w = new ObjectMapper()
            .writer()
            .with(pp);

It will output the JSON with the format like :

{
  "users":[{
    "name":"u1",
    "age":10
  },{
    "name":"u2",
    "age":20
  }]
}

Upvotes: 5

Related Questions