Reputation: 365
This is very simple: Using Android Studio, I can't build a project because I'm getting the error:
Error: java: unreported exception org.json.JSONException; must be caught or declared to be thrown
Here is the offending code:
public static JSONObject toJsonObject(String json){ JSONObject jsonObj = new JSONObject(json); return jsonObj; }
I'm importing org.json.JSONObject; by the way.
The squiggly red line is underneath "new JSONObject(json)". It doesn't seem to like being passed a String, but everywhere I've seen e.g. https://github.com/douglascrockford/JSON-java/blob/master/JSONObject.java suggests it can.
I have tried making the class and method non-static, and have rebuilt projhect/restarted Android Studio.
I know this must be something simple I've missed...
Upvotes: 2
Views: 5727
Reputation: 5911
You pretty much always have to wrap all JSONObject and JSONArray usages in try-catch-blocks catching JSONException. In most cases it's boilerplate code that won't ever run. In the case of using new JSONObject(...) and new JSONArray(...), though, the try-catch-block is vital: It throws an exception if the passed String is not a valid JSON string. Make sure you always handle it somehow. In your case I would recommend this (where TAG is the name of your class):
public static JSONObject toJsonObject(String json){
try {
return new JSONObject(json);
} catch (JSONException e) {
Log.e(TAG, "Invalid JSON string: " + json, e);
return null;
}
}
If you don't put a try-catch-block in your toJsonObject(...)-method and instead add "throws JSONException" to the method declaration (which would actually solve the error), the full method would become completely redundant, by the way, because it doesn't do anything the JSONObject constructor doesn't.
Upvotes: 4
Reputation: 984
I think this is because you have not used try-catch or throw in your code. Use try- catch block in your code. And then check if the problem is solved..
Upvotes: 0
Reputation: 2555
You have to use try-catch
or Throw
JSONException
public static JSONObject toJsonObject(String json){
try{
JSONObject jsonObj = new JSONObject(json);
return jsonObj;
}
catch (JSONException e)
{
//do something
}
}
Upvotes: 2