0

Frequently, I extract the data from mongo database using java (because I have to do it across very large number of collection across many databases). In the process, I generally use

Eg:

time = ((myObject.containsField("time"))) ? (myObject.get("time").toString().isEmpty()) ? "Empty" : myObject.get("time").toString() : "NA";

to make sure if the string exists or it is empty. but how do we do a null check, I mean if time has a value null

Eg: time=null

How do we extract the value to script so that I can save it to the extract as some string which represents null value?

.get is resulting in to a NullPointerException. This is a run time check and I often extract more than 20 values for each record. What is the best way to do a null check?

your help is much appreciated. Thanks in advance!! :)

6
  • Do you want the resulting time to be a String "null" or null Commented May 27, 2015 at 12:13
  • I want it to be racta string "null". so that I can save it as a value of time for a record Commented May 27, 2015 at 12:15
  • Ok, then the below answer should work for you. Commented May 27, 2015 at 12:16
  • it is not working patrick Commented May 27, 2015 at 12:21
  • Need to find out where the NPE is actually coming from then... if myObject isn't null, then the returned .get("time") object is.. thus .get() isn't throwing the NPE, but toString() is.. I'll modify the answer below. Commented May 27, 2015 at 12:45

1 Answer 1

1

If .get() is throwing the the null pointer exception you could simply add another ternary case around it, for .get() to throw an NPE myObject must be null. Thus, this should work

time = myObject != null ? ((myObject.containsField("time")))?
       (myObject.get("time").toString().isEmpty())?"Empty":myObject.get("time").toString():"NA" : "null";

To account for the above comments, .get doesn't appear to be what is throwing the NPE, .toString() must be. Alter the code thusly:

time = myObject.containsField("time") ? myObject.get("time") != null ?
       (myObject.get("time").toString().isEmpty())?"Empty":myObject.get("time").toString():"NA" : "null";

The extra ternary block, will now check if the resulting "time" key results in a null pointer.

Sign up to request clarification or add additional context in comments.

1 Comment

Its not working myObject is a DBObject. comparing myObject seems to be a not logical one as myObject will be having more than one columns to extract. I tried extracting it in the way you suggested but it is still failing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.