2

Is there a proficient way to set a string to some default value if assignment gives nullPointerException?

Say im initializing a string like this:

String myString= jsonElement.getAsJsonObject().get("myString").getAsString();

If it gives nullPointer i need to give it a default value, i know i can do it with an "if" check after but is that the only way? It would mean alot of checks as i am initiating around 20 strings.

Is there any way to do it like:

String myString = jsonElement.getAsJsonObject().get("myString")
    .getAsString() || "defaultValue";
3
  • 2
    "as i am initiating around 20 strings" ... when you what to get JSON data into variable, then you should use a proper JSON parser like Jackson or gson, instead of doing that yourself. Commented May 18, 2017 at 15:36
  • What's the return type of getAsJsonObject()? Commented May 18, 2017 at 16:08
  • @steffen The return type of getAsJsonObject() is a JsonObject Commented May 18, 2017 at 16:13

2 Answers 2

5

You can use Optional for that, as in:

Optional.of(jsonElement).map(element -> element.getAsJsonObject()).map(o -> o.get("myString")).map(e -> e.getAsString()).orElse("defaultValue");
Sign up to request clarification or add additional context in comments.

1 Comment

Put all the cases in an array. Loop over the array calling this with the elements of the array in the "myString" part.
1

How about make a method to do that.

String getOrDefault(JsonElement jsonElement, String key)
    JsonObject obj = jsoneElement.getAsJsonObject().get(key);
    return obj==null?"default":obj.getAsString();
}

1 Comment

This looks like a good way to do it, and in my case i will have the same default value for all strings.

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.