By
using gson, we can validate, whether given string is valid JSON or not.
import com.google.gson.*; public class JsonValidate { private static final Gson gson = new Gson(); static boolean isValidJSON(String str){ try { gson.fromJson(str, Object.class); return true; } catch(com.google.gson.JsonSyntaxException ex) { return false; } } public static void main(String args[]){ String validStr = "{\"org\":[{\"name\":\"Honeywell\",\"yrsOfExperience\":2.2}," + "{\"name\":\"IBM\",\"yrsOfExperience\":1.8}],\"firstName\":\"Krishna\"," + "\"lastName\":\"Hari\",\"salary\":80000.0}"; String inValidStr = "{\"org\":[{\"name\":\"Honeywell\",\"yrsOfExperience\":2.2}," + "{\"name\":\"IBM\",\"yrsOfExperience\":1.8}],\"firstName\":\"Krishna\"," + "\"lastName\":\"Hari\",\"salary\"}"; System.out.println(isValidJSON(validStr)); System.out.println(isValidJSON(inValidStr)); } }
Output
true false
No comments:
Post a Comment