Reputation: 1394
Is there a way in Java to build a JSONObject without having to deal with an exception? Currently I'm using the default constructor, which however forces me to put try/catch blocks in the code. Since in the rest of the code I'm using the "opt" version of get, checking if the return value is null, is there a way to build the object in the same way? (that is, some kind of constructor that returns null if it can't build the json from a string).
Example:
try {
JSONObject temp = new JSONObject(someString);
} catch (JSONException e) {
e.printStackTrace();
}
What I would like to do:
JSONObject temp = ??????(someString);
if(temp != null) {...}
Upvotes: 1
Views: 4250
Reputation: 2820
You need to create the method manually, as any parser will most probably throw one or the other Exception
in case of any discrepancy.Try something like this:-
public JSONObject verifyJSON(String inputString){
JSONObject temp;
try {
temp = new JSONObject(inputString);
} catch (JSONException e) {
temp = null;
e.printStackTrace();
}
return temp;
}
Then you can do :-
JSONObject temp = verifyJSON(someString);
if(temp != null) {...}
Upvotes: 3