0

I know that most Java json libraries can pretty print by

  • parsing into a generic model and then
  • serialising the model.

There are endless existing questions on StackOverflow which tell you to pretty print json this way using Jackson or GSON, e.g Pretty-Print JSON in Java

However, I have found with using Jackson ObjectMapper to do this, if I have decimal value eg "10000.00" it will then parse them into either a BigDecimal or Double and then end up writing it as "10000.0" (double) or "1E+4" (BigDecimal).

What I want is a way of formatting JSON which only affects whitespace, and does not disturb the content of any values - if the input was "10000.00" the output must be "10000.00"

Does anyone know of a Java JSON library that can handle that?

user1791121
  • 328
  • 3
  • 8
  • can you show the code – pvpkiran Aug 10 '18 at 08:32
  • Code for using ObjectMapper is shown in the linked question, but that doesn't do what I want. `ObjectMapper mapper = new ObjectMapper(); System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject))` – user1791121 Aug 12 '18 at 23:48

2 Answers2

1

Underscore-java library has static method U.formatJson(json). It will leave the double value as is. 12.0 will be formatted as 12.0. I am the maintainer of the project.

Valentyn Kolesnikov
  • 2,029
  • 1
  • 24
  • 31
-1

There is a difference between JSONs {"value":5.0} and {"value":"5.0"} in the second case the "5.0" value will be treated as String and will not be modified. In the first case, it will be detected as Numerical and may be modified. So, either make a requirement for your JSON to have numerical values quoted, or do it yourself in your code before parsing the JSON string. Also if you yourself produce the JSON from some object then if you have

private Double myValue;

Have the getter

@JsonIgnore
Double getMyValue() {
  return myValue;
}

and add another getter

  @JsonProperty(name="myValue")
  String getMyValueStr() {
    return myValue.toString();
  }

All annotations are for Jason-Jackson.

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36
  • In my case I have no model classes. So hacking the model wouldn't help. In any case, I want to avoid the entire parsing/serialising issue and find a tool which specialises in formatting. – user1791121 Feb 16 '20 at 23:50