Skip to content

Commit

Permalink
#691 JSON Pretty print
Browse files Browse the repository at this point in the history
  • Loading branch information
yanchevsky committed Mar 12, 2018
1 parent dadffbc commit 669bc0b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,19 @@ public static Map[] toMaps(String json) {
* @return JSON string.
*/
public static String toJsonString(Object val) {
return toJsonString(val, false);
}

/**
* Convert Java object to a JSON string.
*
* @param val Java object
* @param pretty enable/disable pretty print
* @return JSON string.
*/
public static String toJsonString(Object val, boolean pretty) {
try {
return mapper.writeValueAsString(val);
return pretty ? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(val) : mapper.writeValueAsString(val);
} catch (Exception e) {
throw new RuntimeException(e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,16 @@ public void setLastName(String lastName) {
a(toJsonString(new Person("John", "Smith"))).shouldBeEqual("{\"firstName\":\"John\",\"lastName\":\"Smith\"}");
}

@Test
public void shouldConvertObject2JSONPrettyPrintString() {
Map m = JsonHelper.toMap("{ \"name\" : \"John\", \"age\": 22 }");
String pretty = "{" + System.lineSeparator() +
" \"name\" : \"John\"," + System.lineSeparator() +
" \"age\" : 22" + System.lineSeparator() +
"}";
a(toJsonString(m, true)).shouldBeEqual(pretty);
}

@Test
public void shouldConvertArray2List() {
List l = JsonHelper.toList("[1, 2]");
Expand Down

0 comments on commit 669bc0b

Please sign in to comment.