Home > Net >  Remove trailing whitespace from JSON key output with Jackson Deserialized POJO in Springboot
Remove trailing whitespace from JSON key output with Jackson Deserialized POJO in Springboot

Time:07-08

In Springboot I have a class that is converting a POJO to a JSON file

public class GoogleJSONAuthWriter {

public void writeGoogleAuthPropertiesToJSON(GoogleAuthProperties googleAuthProperties) throws IOException {

    // create object mapper instance
    ObjectMapper mapper = new ObjectMapper();

    // convert map to JSON file
    mapper.writerWithDefaultPrettyPrinter().writeValue(Paths.get("key.json").toFile(), googleAuthProperties);

}

}

It is producing this file:

{
  "type" : "service_account",
  "project_id" : "secret-walker-355609",
}

I need it to produce this format file:

{
  "type": "service_account",
  "project_id": "secret-walker-355609",
}

So I need to remove the single space after each key but retain the single space on the other side of the ':'

Is there a pain free way to do this or do I need to write a custom deserializer? I have no experience of doing the latter so if that is the case how should I do that?

CodePudding user response:

It looks like the best way with Jackson is to override the DefaulPrettyPrinter.

You will need at minimum Jackson version 2.9

public class ExtendedPrettyPrinter extends DefaultPrettyPrinter {

  public ExtendedPrettyPrinter() {
    _objectFieldValueSeparatorWithSpaces = ": ";
  }

  private ExtendedPrettyPrinter(ExtendedPrettyPrinter extendedPrettyPrinter) 
 {
    super();
  }

  @Override
  public DefaultPrettyPrinter createInstance() {
    return new ExtendedPrettyPrinter(this);
  }
}

The following is how to use the new pretty printer

mapper.writer(new ExtendedPrettyPrinter()).writeValue(Paths.get("key.json").toFile(), googleAuthProperties); 

CodePudding user response:

https://jenkov.com/tutorials/java-json/gson.html

Specifically

Gson gson = new GsonBuilder().setPrettyPrinting().create();

Got me the Google format json I was looking for

  • Related