Skip to content

Commit

Permalink
#698 JsonHelper: Alphabetical sorting of fields in "pretty print" mode
Browse files Browse the repository at this point in the history
  • Loading branch information
yanchevsky committed Mar 16, 2018
1 parent 314e415 commit a463b7d
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public static String toJsonString(Object val) {
*/
public static String toJsonString(Object val, boolean pretty) {
try {
return pretty ? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(val) : mapper.writeValueAsString(val);
return pretty ? mapper.writerWithDefaultPrettyPrinter().with(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS).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 @@ -44,12 +44,15 @@ public void setLastName(String lastName) {

@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);
Map m = JsonHelper.toMap("{ \"firstName\" : \"John\",\"lastName\" : \"Smith\", \"age\": 22, \"1\": 1 }");
String pretty = toJsonString(m, true);
a(pretty).shouldBeEqual("{" + System.lineSeparator() +
" \"1\" : 1," + System.lineSeparator() +
" \"age\" : 22," + System.lineSeparator() +
" \"firstName\" : \"John\"," + System.lineSeparator() +
" \"lastName\" : \"Smith\"" + System.lineSeparator() +
"}"
);
}

@Test
Expand Down

0 comments on commit a463b7d

Please sign in to comment.