简体   繁体   中英

Java string set default value if null

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";

您可以为此使用Optional ,如下所示:

Optional.of(jsonElement).map(element -> element.getAsJsonObject()).map(o -> o.get("myString")).map(e -> e.getAsString()).orElse("defaultValue");

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM