luigi7up
luigi7up

Reputation: 5962

Java exception handling (example with json)

First, I would like to say I'm sorry for such an ambiguous title...

I would like to know how to handle exceptions in the following scenario... I have a Struts action that receives a string from a EJB:

try{       
  JSONObject data = new JSONObject(result);   //result is String 
  String gatewayId = data.getString("gatewayId");
  session.setAttribute("gatewayId", gatewayId);
}catch(Exception e){
  System.out.println(e.getMessage());
}

EDIT Imports are:

import org.apache.struts2.json.*;
import org.json.*;

In case A json is:

{"gatewayId":100, "mask":4}

In case B json is:

{"success":false, "errorDesc":"bla bla"}

If the gatewayId is in the JSON I have no problem, but the problem is that the JSON received from EJB can (but doesn't have to) have that key:value pair.

If there was a Boolean JsonObject.hasString() method I would have no exceptions thanks to checking the existance of the string first in if/else if statements, but this way I can't avoid exceptions...

The first thing I thought I could do was to have different catch blocks depending on the exception type, but it seems that all exceptions are of generic JSONException type and also I shouldn't put any JSON treating code in the catch block because that code could also be throwing it's exceptions.

Please, have in mind that I'm not looking for the exact solution of my JSON problem here, but rather a general explanation of how to solve this kind of problems when you don't have functions that help you avoid having exceptions...

I hope my question makes sense....

Upvotes: 2

Views: 4111

Answers (1)

Pankaj Singhal
Pankaj Singhal

Reputation: 16043

try

data.has("gatewayId");

this would help.

Upvotes: 3

Related Questions