JsonUtils { public static boolean isValidJson(String jsonString) { if(StringUtils.isBlank(jsonString)) { return false; } try { jsonParser.parse(jsonString); return true; } catch (JsonSyntaxException jse) { return false; } }  static boolean isValidJson(String jsonString); static JsonParser jsonParser; }
@Test public void testIsValidJson() throws Exception { Assert.assertFalse(JsonUtils.isValidJson(null)); Assert.assertFalse(JsonUtils.isValidJson("")); Assert.assertFalse(JsonUtils.isValidJson("{")); Assert.assertFalse(JsonUtils.isValidJson("}")); Assert.assertTrue(JsonUtils.isValidJson("{}")); Assert.assertTrue(JsonUtils.isValidJson("{ \"stack\" : \"HDP\" }")); Assert.assertTrue(JsonUtils.isValidJson("{\n" + " \"stack_selector\": [\"hdp-select\", \"/usr/bin/hdp-select\", \"hdp-select\"],\n" + " \"conf_selector\": [\"conf-select\", \"/usr/bin/conf-select\", \"conf-select\"]\n" + "}")); Assert.assertFalse(JsonUtils.isValidJson("{\n" + " \"stack_selector\": [\"hdp-select\", \"/usr/bin/hdp-select\", \"hdp-select\"],\n" + " \"conf_selector\": [\"conf-select\", \"/usr/bin/conf-select\", \"conf-select\"]\n" + "")); }