I have a super simple line:
JSONObject params = new JSONObject("{\"values\": { \"barcode\": \"testing\" } }");
Android studio tells me that this line 'throws JSONException', but why? I must be doing something stupid here. Any help is appreciated
I have a super simple line:
JSONObject params = new JSONObject("{\"values\": { \"barcode\": \"testing\" } }");
Android studio tells me that this line 'throws JSONException', but why? I must be doing something stupid here. Any help is appreciated
JSONException is a checked exception. This means that you need to have code in place to deal with it. You need to either catch the exception or let it bubble up by declaring throws JSONException on your method.
This is the case for all checked exceptions in Java (all exception except those that extend RuntimeException).
In your case, since the String is constant and correct, I would do
} catch ( JSONException e) {
// should never happen
throw new IllegalArgumentException("unexpected parsing error",e);
}
This will convert the JSONException (if for some reason it does happen after all) into an (unchecked) RuntimeException.
public JSONObject(String source) throws JSONException {
this(new JSONTokener(source));
}
You are using above method/constrcutor to create your JSONObject and its saying in its signature that it throws JSONException so you can't simply do what you have done ,
JSONObject params = new JSONObject("{\"values\": { \"barcode\": \"testing\" } }");
You need to enclose above line in Java try- catch since method signature is clearly specifying a checked Exception so you need to handle that in try catch.
try{
JSONObject params = new JSONObject("{\"values\": { \"barcode\": \"testing\" } }");
}catch(JSONException ex){
//eat or rethrow your exception
}
You have to note that there are other JSONObject constructors which doesn't specify any checked exceptions so you can use those in a simple line, like you did but the one you are trying to use specifies a checked exception so you need to handle that - otherwise your code won't compile.