3

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?

AncientSwordRage
  • 7,086
  • 19
  • 90
  • 173

2 Answers2

4

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...
Kasun Siyambalapitiya
  • 3,956
  • 8
  • 38
  • 58
Andy
  • 983
  • 7
  • 13
1

Just use try and catch block to handle it........

try{

strippedJSON.put("userLocation", incomingUser.get("location").toString();



}catch(Exception ex){

  System.out.println("This field is null");

}
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
  • Ol, sure but wouldn't it make more sense to put something sensible into the JSON file there? Isn't that an abuse of the `try{}catch(){}` block? – AncientSwordRage Oct 04 '12 at 14:56
  • 1
    @Pureferret till now all the JSON i have encountered are provided to be my some webservice.... so the coding of JSON was not in my hand, But some how i needed to handle it..and try and catch was the way i did it... – Kumar Vivek Mitra Oct 04 '12 at 15:01
  • @Pureferret The whole of Java is abuse of the `try{}catch(){}` block – Kevin Mar 31 '17 at 17:36