I had a requirement to check whether a given string is valid JSON or not in Java.
My simple method for that using google gson was:
public static boolean isValidJson(String str) {
try {
gson.fromJson(str, Object.class);
return true;
} catch(com.google.gson.JsonSyntaxException ex) {
return false;
}
}
We can use any JSON parser for the same logic, but I haven't seen any inbuilt method to validate json.
Another classic example would be, a custom function to check for number:
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
My problem is: Is it OK to use exceptions for logics in such manner? OR is it a bad practice?