Try Catch in Java | Json still crashes - java

try {
Log.e("getTrackerSettings | ", json);
trackerSettings = new Gson().fromJson(json, typeToken);
} catch ( IllegalStateException e) {
Log.e("getTrackerSettings inside catch | ", "");
e.printStackTrace();
trackerSettings = new TrackerSettings(1, "Hello", "73");
}
This code snippet will crash, and give the following:
E/getTrackerSettings inside try |: false
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sendiman.manager, PID: 13196
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BOOLEAN at line 1 column 6 path $
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226)
at com.google.gson.Gson.fromJson(Gson.java:932)
at com.google.gson.Gson.fromJson(Gson.java:897)
at com.google.gson.Gson.fromJson(Gson.java:846)
As you can see, this does no make sense. The entire function is inside a larger try catch( Exception e) as well.

The fromJson method throws a com.google.json.JsonSyntaxException. It does not throw a java.lang.IllegalStateException. You're catching the wrong thing.
The text highlights why the JSON is bad, and that IllegalStateException came up as part of parsing it. It's a causal relationship. Think of exceptions not as 'this specific thing went wrong', but as an alternate return value. The fromJson call returns either a T object (the thing you're trying to parse), OR a JsonSyntaxException, and that JsonSyntaxException object (exceptions are just objects) contains the details. You can query it by assigning it to a variable, and its toString also just prints the details. 'some inner parsing code threw an IllegalStateException' is the detail here.
It looks like you're attempting to parse the string "true" or "false" as json. It's not valid JSON, in the sense that all JSON has to be a JSON object in its outermost level.
Replace catch (IllegalStateException) with catch (JsonSyntaxException) instead.

luk2302 Answered in comments.
Catch (JsonSyntaxException e)did catch the crash.

It still fail because you are trying to catch IllegalStateException and not JsonSyntaxException
From javadoc documentation the signature of fromJson is:
public <T> T fromJson(String json, Class<T> classOfT) throws JsonSyntaxException
try {
Log.e("getTrackerSettings | ", json);
trackerSettings = new Gson().fromJson(json, typeToken);
} catch (JsonSyntaxException e) {
Log.e("getTrackerSettings inside catch | ", "");
e.printStackTrace();
trackerSettings = new TrackerSettings(1, "Hello", "73");
}

Related

Get a custom error message, instead of 500

I have a service that looks like this:
public String storeTestRequest(Map<String, String> data, HttpSession session) {
JSONObject json = new JSONObject(data);
boolean hasHealthInsurance = json.getAsString("hasHealthInsurance").equals("true");
try {
this.testRequestRepository.save(new TestRequest(
json.getAsString("firstname"),
json.getAsString("surname"),
json.getAsString("street"),
hasHealthInsurance
));
return "All good.";
}
catch (Exception e) {
return "Something went wrong.";
}
}
In this example, I am saving the values of 4 fields but in fact there are much more and I don't want to validate any of them. So if all values could be saved successfully, I should get the message All good. But if some values are missing, I should get the message Something went wrong..
I have tried it with try & catch but I still get a 500 error.
Your hasHealthInsurance property is empty or null. Your exception message says it's caused by this line.
boolean hasHealthInsurance = json.getAsString("hasHealthInsurance").equals("true");
If you put this line in your try catch block, you will see the exception message in the catch block.

Android - Parsing a JSON string

I'm trying to parse a simple JSON string
try {
String candyJson = "{\"candies\":[ {\"name\":\"Jelly Beans\", \"count\":10}, {\"name\":\"Butterscotch\", \"count\":6}]}";
JSONObject candiesJSONobject = new JSONObject(candyJson);
JSONArray candiesJSONarray = candiesJSONobject.getJSONArray("candies");
Log.v("JSONObject", candiesJSONarray.getJSONObject(0).getString("name"));
} catch (JSONException e){
Log.e("MYAPP", e.toString());
}
The code works fine in this state without catching any exception and prints JSONObject name in the Android Log.
However when I don't try to catch the exception as shown in the following example:
String candyJson = "{\"candies\":[ {\"name\":\"Jelly Beans\", \"count\":10}, {\"name\":\"Butterscotch\", \"count\":6}]}";
JSONObject candiesJSONobject = new JSONObject(candyJson);
JSONArray candiesJSONarray = candiesJSONobject.getJSONArray("candies");
Log.v("JSONObject", candiesJSONarray.getJSONObject(0).getString("name"));
Android Studio gives me unhandled exception error on all JSON methods. Is it necessary to catch JSONException when parsing a JSON or am I doing something wrong?
This is a Java feature actually :-) Please read more about it here.
The idea is that - if a method states that it will throw an (non-Runtime) Exception, all the calls of that method are required to catch this exception, just in case.
It does not mean that you are getting this exception in your code, you can only see that when you actually run it. But Java requires you to be prepared for a situation where such exception is thrown.
Well since you're working with the org.json... json objects, yes most of their methods do throw exceptions that you must catch and handle.
However if you don't want to handle each exception on it's own i suggest you create a json utils class that will handle those things for you.
For example for the JSONObject constructor you can make your own method like so
public static JSONObject createObjectFromString(String objectString) {
try {
return new JSONObject(objectString);
} catch (JSONException e) {
Log.e("MYAPP", e.toString());
}
}
and just reuse this method when you want to create a new json object.
Yes actually if any method is throwing Exception you need to catch that Exception.
This is called as Checked Exceptions or Compile Time Exceptions.
In your case methods like
JsonArray getJsonArray(String name)
or
JsonObject getJsonObject(String name)
check here http://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html#getJsonArray-java.lang.String-
are throwing ClassCastException So you either catch it or throw the exception.
Throwing Exception will lead to crash the app, So better Catch it.
If any method throws checked Exception, then caller can either handle this exception by catching it or can re throw it by declaring another throws clause in method declaration.
This is the reason Android Studio is showing unhandled exception error.

unhandled exception org.json.jsonexception

I'm working on an android app, and the app must save a java object in json format into the SQLite database. I wrote the code for this operation, then they must extract the Json object and reconvert it into a Java Object.
When I try to call the method for deserializing the json object in to a string, I found this error in Android Studio:unhandled exception org.json.jsonexception
When I try to catch JSONException e the program runs but don't deserialize the json object.
This is the code for the method:
private void read() throws JSONException {
SQLiteDatabase db = mMioDbHelper.getWritableDatabase();
String[] columns = {"StringaAll"};
Cursor c = db.query("Alle", columns, null, null, null, null,null );
while(c.moveToNext()) {
String stringaRis = c.getString(0);
JSONObject jObj = new JSONObject(stringaRis);
String sPassoMed = jObj.getString("passoMed");
final TextView tView = (TextView) this.findViewById(R.id.mainProvaQuery);
tView.setText(sPassoMed);
// }
}
}
Can you help me please?
Yes, you need to catch the exception.
But when you catch it, you should not just throw it on the floor. Your application needs to do something about the exception. Or if you / it is not expecting an exception to occur at runtime, then at least you should report it. Here's a minimal example (for an Android app)
try {
...
JSONObject jObj = new JSONObject(stringaRis);
...
} catch (JSONException e) {
Log.e("MYAPP", "unexpected JSON exception", e);
// Do something to recover ... or kill the app.
}
Of course, this does not solve your problem. The next thing you need to do is to figure out why you are getting the exception. Start by reading the exception message that you have logged to logcat.
Re this exception message:
org.json.JSONException: Value A of type java.lang.String cannot be converted to JSONObject
I assume it is thrown by this line:
JSONObject jObj = new JSONObject(stringaRis);
I think that it is telling you is that stringaRis has the value "A" ... and that cannot be parsed as a JSON object. It isn't JSON at all.

Continue processing when an Exception occurs

I have the below code that basically reads a bunch of JSON strings, and converts them to a java object. My problem is if at any point, the transformation fails for any of the JSON strings, it doesn't process the others strings. What I need is -
Find the string for which the error occured.
In the exception block do something to continue processing.
Here is my code to convert from JSON to Java.
public static <T> T convertToObject(String jsonString,Class<T> classType){
T obj = null;
try {
obj = objectMapper.readValue(jsonString, classType);
} catch (Exception e) {
throw new Exception("Unable to convert to DTO :" + e.getMessage(), e);
}
return obj;
}
I think you need a custom deserializer. Standard ObjectMapper will do all or nothing. Read more about creating a custom deserializer for Jackson ObjectMapper here:
http://www.baeldung.com/jackson-deserialization

how do i figure out how to debug this? HttpResponse

I'm trying to make a json object from the result of the googleplaces api. But one line of code is causing me alot of problems. My question is how the heck do i find what the issue is. I can't seem to catch the right exception (im a noob at debugging though). The url that i am passing in has the value:
https://maps.googleapis.com/maps/api/place/search/json?location=34.7,-86.5&radius=16000&types=food&name=mcdonalds&sensor=true&key=(myApiCodeWhichImNOTPostingHere)
^i do have the correct apicode and the link works ourside of android.
here is the method in question (highlighted is the line that is causing problems).
public static JSONObject getTheJSON(String url){
JSONObject json=null;
try{
DefaultHttpClient myHttpClient = new DefaultHttpClient();
HttpPost myHttpPost = new HttpPost(url);
//this line below is giving me problems (jumps streight to the catch Exception)
HttpResponse response = myHttpClient.execute(myHttpPost);
//this line above is giving me problems(jumps streight to the catch Exception)
String data = EntityUtils.toString(response.getEntity());
json= new JSONObject(data);
//parse the JSONObject
} catch (UnsupportedEncodingException e){e.printStackTrace();}
catch (ClientProtocolException e){e.printStackTrace();}
catch (IOException e){e.printStackTrace();}
catch (JSONException e) {e.printStackTrace();}
catch (NullPointerException e){ Log.e("My APP", "exception: " + e.getMessage());}
/* jumps to line below (skips the other catch exceptions)
the log reads "null" since i use the "getMessage()" so thats not useful*/
catch (Exception e ) { Log.e("My APP", "exception: " + e.getMessage());}
return json; // returning the JSON object
}
(Edit):
Here is the logcat. i think im getting a connection to factory client error
10-16 21:11:30.105: E/My APP(980): exception
10-16 21:11:30.345: E/MapActivity(980): Couldn't get connection factory client
Instead of using e.getMessage(), use e.printStackTrace() (outside of the Log.e() method, but within the catch clause) so you can trace what the real problem is. If you do not get any wiser from that, please post the stacktrace here.
Edit (see commments):
My LogCat (without filters) always displays the stacktraces in a correct way, but after a bit of searching it seems that that is not always the case:
See this SO question.
You should use three(!) arguments with the Log.e method.
Example:
Log.e("My APP", "exception", e);
You might want to check your SSL setup. You are calling a https:// url
I ran your code in eclipse and it ran fine giving me a valid response. I think this is probably SSL related. You could enable SSL debugging by doing -Djavax.net.debug=all
Can you paste the output log after enabling SSL debugging?

Categories

Resources