I'm ingesting tweets in JSON using JSON-Simple. I split the user object off into it's own JSONObject class, in memory:
incomingUser = (JSONObject) incomingTweet.get("user");
Then I'm stripping off various fields from the tweet and the user objects using JSON-Simple; I was doing
strippedJSON.put("userLocation", incomingUser.get("location").toString();
But it turns out that occasionally a user's location is set to null
.
So now I'm checking to see if the field I'm stripping is null, and setting it to "":
strippedJSON.put("userLocation", (incomingUser.get("location").toString().equals(null)?
"": incomingUser.get("location").toString());
But I've stepped through eclipse in debug mode and found someone who's location is set to null, and stepped over the part where I strip out the JSON object field associated with "location"
and put it into the JSON object field "user Location"
. And I get a NPE.
Does my ternary statement not account for that? I'd have though it would check if it was equal to null (there only being one 'null object' it should be able to see the pointers are the same) if it is (condtion?
is true) it should evaluate to put("location","")
no?
Where am I going wrong? What should I do instead to handle this null value?
You are getting a Null Pointer Exception because you are attempting to access the .equals() method on a null object.
Instead try this if the location
key returns a value:
(incomingUser.get("location").toString() == null) ? etc..
Edit: Actually its just occured to me that maybe incomingUser.get("location")
returns null
( ie. the location
key may be referring to an JSONObject
or JSONArray
), in which case you need:
(incomingUser.get("location") == null) ? etc...