@Test public void testJsonGeneration() { Map<String, Object> map = new LinkedHashMap<>(); map.put("first", null); map.put("second", 1); map.put("third", true); Map<String, Object> nested = new LinkedHashMap<>(); nested.put("first", "value \"with quotes\""); Collection<?> collection = asList("one", 2, false, "four", nested); map.put("collection", collection); map.put("emptyMap", new HashMap<>()); map.put("emptyCollection", new ArrayList<>()); assertThat(toJson(map)).isEqualTo( "{" + "\"first\":\"\"," + "\"second\":1," + "\"third\":true," + "\"collection\":[" + "\"one\"," + "2," + "false," + "\"four\"," + "{" + "\"first\":\"value \\\"with quotes\\\"\"" + "}" + "]," + "\"emptyMap\":{}," + "\"emptyCollection\":[]" + "}"); }
public static String toJson(Collection<?> collection) { if (collection == null) { throw new IllegalArgumentException("Method parameter collection must not be null"); } return collection.stream() .map(JsonUtil::toJson) .reduce((l, r) -> l + "," + r) .map(s -> '[' + s + ']') .orElse("[]"); }
JsonUtil { public static String toJson(Collection<?> collection) { if (collection == null) { throw new IllegalArgumentException("Method parameter collection must not be null"); } return collection.stream() .map(JsonUtil::toJson) .reduce((l, r) -> l + "," + r) .map(s -> '[' + s + ']') .orElse("[]"); } }
JsonUtil { public static String toJson(Collection<?> collection) { if (collection == null) { throw new IllegalArgumentException("Method parameter collection must not be null"); } return collection.stream() .map(JsonUtil::toJson) .reduce((l, r) -> l + "," + r) .map(s -> '[' + s + ']') .orElse("[]"); } private  JsonUtil(); }
JsonUtil { public static String toJson(Collection<?> collection) { if (collection == null) { throw new IllegalArgumentException("Method parameter collection must not be null"); } return collection.stream() .map(JsonUtil::toJson) .reduce((l, r) -> l + "," + r) .map(s -> '[' + s + ']') .orElse("[]"); } private  JsonUtil(); static String toJson(Collection<?> collection); static String toJson(Map<?, ?> map); }
JsonUtil { public static String toJson(Collection<?> collection) { if (collection == null) { throw new IllegalArgumentException("Method parameter collection must not be null"); } return collection.stream() .map(JsonUtil::toJson) .reduce((l, r) -> l + "," + r) .map(s -> '[' + s + ']') .orElse("[]"); } private  JsonUtil(); static String toJson(Collection<?> collection); static String toJson(Map<?, ?> map);  }