Reputation: 171
I have a block of JSON data as follows: (simplified for readibility):
{"placeName":"Paris",
"sectionCode":"",
"elapsed":"FT",
"Time":"02/24/2015 17:30:00",
"Date":"02/24/2015 00:00:00",
"Score":"1 : 1",
"statusCode":6};
I am using the GSON library (see https://code.google.com/p/google-gson/) in order to process this JSON in a java program.
The problem I am encountering is with the sectionCode attribute (the second element in the list above). In other JSON blocks of data that I am processing, this element either does not exist, or does exist, and contains an integer as its value e.g. 14. This causes no problems. Here, however, the value for the sectionCode is simply "".
Below is the code I currently use to process this segment of the JSON block (where jsonroot
contains the block of JSON data):
//deal with situation where no section code is provided
Integer sectioncode = null;
if ((jsonroot.get("sectionCode") != null) && (jsonroot.get("sectionCode").getAsString() != null) && (!jsonroot.get("sectionCode").isJsonNull()) && (jsonroot.get("sectionCode").getAsString() != "") && (!jsonroot.get("sectionCode").equals(null))) {
sectioncode = jsonroot.get("sectionCode").getAsInt();
}
The numerous conditions in the 'if' statement are an attempt to detect the empty string in the value for the sectionCode attribute, and thus prevent the following 'getAsInt' code from executing if this is the case. I expected that it would be caught by at least one of them, but this does not seem to be the case. Instead, when it encounters this part of the code, I get the following error:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at com.google.gson.JsonPrimitive.getAsInt(JsonPrimitive.java:260)
at MyProgram.extract_general_page_data(MyProgram.java:235)
at MyProgram.load_one_page(MyProgram.java:187)
at MyProgram.do_all(MyProgram.java:100)
at MyProgram.main(MyProgram.java:47)
I am aware that I could simply accept that a NumberFormatException is going to take place, and put a try/catch block in to deal with that, but this seems like a messy way to deal with the situation.
So my question is really: Why aren't any of my conditions in the 'if' statement detecting the empty value? And what could I use instead?
Upvotes: 1
Views: 4271
Reputation: 5753
Simply use isJsonNull()
int sectioncode = jsonroot.get("sectionCode").isJsonNull() ? 0 : jsonroot.get("sectionCode").getAsInt();
Upvotes: 2
Reputation: 1377
did you try to use the String length to see if it is zero, such as this,
if ((jsonroot.get("sectionCode") != null) && (jsonroot.get("sectionCode").getAsString().length() != 0))
{
sectioncode = jsonroot.get("sectionCode").getAsInt();
}
Upvotes: 4