why is try catch required for every field in json parsing - java

I see an old method from a colleague of deserializing json object in java where the json is taken as string deserialized and passed the values in an array. What I dont understand about this code is why for every field try and catch method is added and why can't we have a single try and catch because all catch do the same thing of catching the json exception and assigning responseArray[0] to value 1.
Here is the code:
String[] responseArray = new String[4];
Arrays.fill(responseArray, "");
try {
final JSONObject response1 = new JSONObject(response);
try{
responseArray[0] = response1.getJSONObject("body")
.getJSONObject("responseStatus").getString("estado");
}
catch (JSONException e) {
responseArray[0] = "1";
e.printStackTrace();
}
if(!responseArray[0].equalsIgnoreCase("0")){
try{
responseArray[1] = response1.getJSONObject("body")
.getJSONObject("responseStatus")
.getString("codigoRespuesta");
}
catch (JSONException e) {
responseArray[0] = "1";
e.printStackTrace();
}
try{
responseArray[2] = response1.getJSONObject("body")
.getJSONObject("responseStatus")
.getString("descripcionRespuesta");
}
catch (JSONException e) {
responseArray[0] = "1";
e.printStackTrace();
}
}
try{
responseArray[3] = response1.getJSONObject("body")
.getJSONObject("responseData").getLong("esValido")+"";
}
catch (JSONException e) {
responseArray[0] = "1";
e.printStackTrace();
}
} catch (JSONException e) {
responseArray[0] = "1";
e.printStackTrace();
}
return responseArray;

There is no explicit need to add try and catch blocks to every ".getJSONObject" methods.
There are two ways by which you can use exception handling.
1. try-catch blocks. Single try & catch block would work fine as well.
2. Let the method throws JSONException as a replacement to try and catch blocks.
Checked exceptions (like the one in your case) are checked at compile time, and so you need to handle them using either of the two ways
Exception handling reference link

Related

Create JSON file with huge data

Adding backup feature on my app and i am using Realm database, i want to backup it to a json file.
i have created the function for reading the database and create a JSONobject.
While doing the JSONobject.tostring i got a outofmemory error since i have more than 200'000 records.
any other way to create the json file.
RealmResults<StoneModelR> allStones = realm.where(StoneModelR.class).sort("id", Sort.ASCENDING).findAll();
for (StoneModelR singleStone : allStones) {
try {
JSONObject jObjectStone = new JSONObject();
jObjectStone.put("stoneid", singleStone.id);
jObjectStone.put("lat", singleStone.lat);
jObjectStone.put("lng", singleStone.lon);
jObjectStone.put("userid", singleStone.userid);
jObjectStone.put("owner", singleStone.owner);
jObjectStone.put("timestamp", singleStone.timestamp);
jObjectStone.put("stonetype", singleStone.stonetype);
jObjectStone.put("remarks", singleStone.description);
jObjectStone.put("imported", singleStone.imported);
jArrayStones.put(jObjectStone);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
JSONObject stoneObj = new JSONObject();
try {
stoneObj.put("stones", jArrayStones);
} catch (JSONException e) {
e.printStackTrace();
}

Unreachable catch block: Unreachable catch block for InvalidFormatException

I am facing problem while reading data from .xlsx file as the catch (InvalidFormatException e) return error for exception as "Unreachable catch block for InvalidFormatException. This exception is never thrown from the try statement body"
I have used openxml4j import which I think is necessary
public static Object[][] getTestData(String sheetname) {
FileInputStream file = null;
try {
file = new FileInputStream(TEST_DATA_SHEET_PATH);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
book = WorkbookFactory.create(file);
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
It is expected that there should not be error for the InvalidFormatException and data should be red from .xlsx file
try {
book = WorkbookFactory.create(file);
} catch (InvalidFormatException e) {
e.printStackTrace();
}
The code inside this try block, does not throw an InvalidFormatException. That is why you are getting the error message.
Perhaps your intention is using that catch block somewhere else.
From the documnetation:
https://poi.apache.org/apidocs/dev/org/apache/poi/ss/usermodel/WorkbookFactory.html#create-java.io.File-
This is the methods signiture:
public static Workbook create(java.io.File file)
throws java.io.IOException,
EncryptedDocumentException
As you can see above, no InvalidFormatExceptionis thrown from this method.
This happens if the IDE can't see or understand that a specific ( InvalidFormatException ) exception is thrown in a given code segment.
You can simply solve this problem by joining you try blocks:
try {
book = WorkbookFactory.create(file);
} catch (Exception e) {
e.printStackTrace();
}
with this approach you can also could clean up and join your code like this if your error handling allows it:
try {
file = new FileInputStream(TEST_DATA_SHEET_PATH);
book = WorkbookFactory.create(file);
} catch (Exception e) {
e.printStackTrace();
}

How to create a complex Json structure manually in android without using API?

I would like to create a Json structure manually using JsonObject and JsonArrays like the below:
{
"data":[
{
"company_name":"xyz",
"Amount":"$2000",
"Duplicate_amount":"$500"
},
{
"company_name":"abc",
"Amount":"$5000"
},
{
"company_name":"zzz",
"Amount":"$2500",
"Duplicate_amount":"$1000"
}
]
}
The Json above is to be generated based on a checking done on an Arraylist. For example: Arraylist [xyz,abc,zzz,xyz,hhh,zzz]. Now I want to check, if the arraylist contains duplicate elements i.e here "xyz" and "zzz" then in the Json structure, the Duplicate_amount Json object to be added in the Json. Else if no duplicate present then only "company_name" and "amount" to be formed. The whole json format to be formed in this way.
How to do it? I have the logic for finding duplicate elements. But I cannot seem to find the logic for forming the above json based on the checking.
Thank you
Updates
So far I have tried this with checking. But the below code doesn't work and is not forming the appropriate json. What is the solution ?:
JSONObject root_jsonObj = new JSONObject();
JSONArray jsonArr = new JSONArray();
JSONObject sub_jsonobj= new JSONObject();
Object[] st = AppData.customer_arr.toArray();
for (Object s : st) {
//The if-else is the duplicate checking part here
if (AppData.customer_arr.indexOf(s) != AppData.customer_arr.lastIndexOf(s)) {
try {
sub_jsonobj.put("name",AppData.customer_arr.get(counter));
sub_jsonobj.put("dup_amount",AppData.amt_arr.get(counter));
} catch (Exception e) {
e.printStackTrace();
}
}
else{
try {
sub_jsonobj.put("name",AppData.customer_arr.get(counter));
sub_jsonobj.put("amount",AppData.amt_arr.get(counter));
} catch (Exception e) {
e.printStackTrace();
}
}
jsonArr.put(sub_jsonobj);
counter++;
}
try {
root_jsonObj.put("data", jsonArr);
} catch (Exception e) {
e.printStackTrace();
}
You can use this one.
JSONObject obj1 = new JSONObject();
try {
obj1.put("company_name", "xyz");
obj1.put("Amount", "$2000");
obj1.put("Duplicate_amount", "$500");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject obj2 = new JSONObject();
try {
obj2.put("company_name", "xyz");
obj2.put("Amount", "$2000");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(obj1);
jsonArray.put(obj2);
JSONObject dataObj = new JSONObject();
dataObj.put("Data", jsonArray);
String jsonStr = dataObj.toString();
System.out.println("jsonString: "+jsonStr);

Intellij Structural Search: How to find empty try catch blocks?

How can i find the empty try catch blocks?
Using the Copy existing template... I found the structural search for try catch:
try {
$TryStatement$;
} catch($ExceptionType$ $Exception$) {
$CatchStatement$;
}
I want to enhance it so that it does only find try catches with empty catch blocks
It should find:
try {
assertTrue(output.validate());
} catch (Exception e) {
//TODO something
}
or
try {
assertTrue(output.validate());
} catch (Exception e) {
}
or
try {
assertTrue(output.validate());
} catch (Exception e) {}
However not:
try {
assertTrue(output.validate());
} catch (Exception e) {
e.printStackTrace();
}
Right now it obviously finds both since there's no differentiation betweens.
How can I add this extra check?
Use the template you have found and on CatchStatement variable set Min count and Max count to 0.

Get jsonvalue without a name

i'm struggling with a JSONObject. I allready returned some json and converted it succesfully to objects and list of objects. My now i'm stuck.
This is the JSONObject i'm getting:
{"Result":true,"Messages":["Goe bezig!"]}
I'm able to get the Messages, but i can't seem to get the boolean in Result. Can somebody explain how to get it plz?
Here is the code:
public boolean Convert(JSONObject json) {
try
{
return json.getBoolean("Result");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
This worked fine for me, although it's pretty vague your question.
String jsonString = "{\"Result\":true,\"Messages\":[\"Goe bezig!\"]}";
JSONObject jsonObject = new JSONObject(jsonString);
boolean result = (Boolean) jsonObject.get("Result");
System.out.println(result);
You might want to catch at the end of your method Exception as well:
try {
return json.getBoolean("Result");
} catch (JSONException e) {
e.printStackTrace(); // replace these with `Log` statement
return false;
} catch (Exception e) {
e.printStackTrace(); // replace these with `Log` statement
return false;
}

Categories

Resources