JsonUtils { public static JsonObject beanToJson(Object bean) { Objects.requireNonNull(bean, CANNOT_CONVERT_NULL_TO_A_JSON_OBJECT); try { return Json.parse(objectMapper.writeValueAsString(bean)); } catch (JsonProcessingException e) { throw new RuntimeException("Error converting bean to JSON", e); } } private  JsonUtils(); static boolean jsonEquals(JsonValue a, JsonValue b); static Stream<T> stream(JsonArray array); static Stream<JsonObject> objectStream(JsonArray array); static DoubleStream numberStream(JsonArray array); static Collector<JsonValue, JsonArray, JsonArray> asArray(); static JsonArray createArray(JsonValue... values); static JsonObject createObject(Map<String, T> map,
            Function<T, JsonValue> itemToJson); static JsonObject beanToJson(Object bean); static JsonArray listToJson(List<?> list); static JsonObject mapToJson(Map<String, ?> map);  }
@Test public void simpleBeanToJson() { JsonObject json = JsonUtils.beanToJson(new SimpleBean()); Assert.assertEquals("value", json.getString("string")); Assert.assertEquals(1.0, json.getNumber("number"), 0.0); Assert.assertEquals(2.3, json.getNumber("flt"), 0.0); Assert.assertEquals(4.56, json.getNumber("dbl"), 0.0); }
@Test public void nestedBeanToJson() { JsonObject json = JsonUtils.beanToJson(new ParentBean()); Assert.assertEquals("parent", json.getString("parentValue")); JsonObject child = json.getObject("child"); Assert.assertEquals("child", child.getString("childValue")); }
@Test public void nullChildBean() { ParentBean bean = new ParentBean(); bean.child = null; JsonObject json = JsonUtils.beanToJson(bean); Assert.assertEquals(Json.createNull(), json.get("child")); }
@Test public void beanWithListAndMap() { ListAndMapBean bean = new ListAndMapBean(); JsonObject json = JsonUtils.beanToJson(bean); JsonObject integerMap = json.getObject("integerMap"); Assert.assertEquals(1, integerMap.getNumber("one"), 0); Assert.assertEquals(2, integerMap.getNumber("two"), 0); JsonObject childBeanMap = json.getObject("childBeanMap"); JsonObject firstChild = childBeanMap.getObject("First"); Assert.assertEquals("firstChildValue", firstChild.getString("childValue")); JsonObject secondChild = childBeanMap.getObject("Second"); Assert.assertEquals("secondChildValue", secondChild.getString("childValue")); JsonArray integerList = json.getArray("integerList"); Assert.assertEquals(3, integerList.get(0).asNumber(), 0); Assert.assertEquals(2, integerList.get(1).asNumber(), 0); Assert.assertEquals(1, integerList.get(2).asNumber(), 0); JsonArray childBeanList = json.getArray("childBeanList"); Assert.assertEquals("firstChildValue", ((JsonObject) childBeanList.get(0)).getString("childValue")); Assert.assertEquals("secondChildValue", ((JsonObject) childBeanList.get(1)).getString("childValue")); }