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";
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");
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();
}
Related
Running a Play! app with Scala. I'm doing a request where the response is expected to be a JSON string. When checking the debugger, the JsonElement returns OK with all information as expected. However, the problem is when I try to actually run methods on that JsonElement.
val json = WS.url("http://maps.googleapis.com/maps/api/geocode/json?callback=?&sensor=true&address=%s", startAddress+","+startCity+","+startProvince).get.getJson
val geocoder = json.getAsString
The only error I get back is Unsupported Operation Exception: null and I've tried this on getAsString and getAsJsonObject and getAsJsonPrimitive
Any idea why it's failing on all methods? Thanks.
I had a similar problem and I had to change jsonObject.getAsString() to jsonObject.toString();
Maybe your JsonElement is a JsonNull
What you could do is to first check that it isn't by using json.isJsonNull
Otherwise, try to get its String representation with json.toString
In my case I just needed to get the element as an empty string if it is null, so I wrote a function like this:
private String getNullAsEmptyString(JsonElement jsonElement) {
return jsonElement.isJsonNull() ? "" : jsonElement.getAsString();
}
So instead of
val geocoder = json.getAsString
You can just use this
val geocoder = getNullAsEmptyString(json);
It returns "" if the element is null and the actual string if it is not
To add to #Henry's answer. In the spirit of Kotlins "OrNull" Adding an extension function:
fun JsonElement.asStringOrNull(): String? {
return if (isJsonNull) null else asString
}
The class JsonElement will throw Unsupported Operation Exception for any getAs<Type> method, because it's an abstract class and makes sense that it is implemented in this way.
For some reason the class JsonObject, does not implement the getAs<Type> methods, so any call to one of these methods will throw an exception.
Calling the toString method on a JsonElement object, may solve your issue in certain circumstances, but isn't probably what you want because it returns the json representation as String (e.g. \"value\") in some cases.
I found out that also a JsonPrimitive class exists and it does implement the getAs<Type> methods. So probably the correct way to proceed is something like this:
String input = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
JsonParser parser = new JsonParser();
JsonElement jsonTree = parser.parse(input);
if(jsonTree != null && jsonTree.isJsonObject()) {
JsonObject jsonObject = jsonTree.getAsJsonObject();
value = jsonObject.get("key1").getAsJsonPrimitive().getAsString()
}
PS. I removed all the nullability mgmt part. If you are coding in Java you probably want to manage this in a better way.
see GitHub source code for JsonElement:
https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/JsonElement.java#L178
Considering this code:
public class Param {
#Text(required = false)
protected String param;
public String getValue() {
return param;
}
}
And I have this xml:
<item key="Key"></item>
After parsing this xml getValue() returns me null instead of empty string.
Why is this Behaviour?
This behavior refer that it found have an empty (not space) value. So the String bind to that not even initialize (will not occupies memory).
as String a=""; is a initialized variable and it have memory allocated on low level. Otherwise there is no need of initialization if it is set empty. It can be costly for enterprise applications for class objects.
MORE
About string is a char array and each char is assosiated with ASCII value
Test it
String a="";
System.out.println(a));
output:
//[B#459bdb65
and
String a;
System.out.println(a));
output:
java.lang.RuntimeException: Uncompilable source code - variable a might not have been initialized
Where about char
char a='A';
System.out.println((int)a);
output:
65
AFAIK the behaviour you're experiencing is the expected with your code.
If you want to make empty element be returned as empty string instead of null, the best way is to build a Converter.
Another way is via annotation and use the behaviour, you can annotate it as required:
#Element(name = "PARAM", required = true)
private String param;
The required = true will throw an exception if drop is empty. You can use this if an empty drop is not allowed.
A second way is set required = false so will be deserialized to null if it's empty:
boolean isEmpty = ( a.getParam() == null );
There is a code :
Long val = 10L
If I want to take its value as a String which approach is correct?
val.toString() or (String)val?
val.toString() would work.
If you are not sure if val can be null, you can also do String.valueOf(val)
You'd do it like this with the String class:
String s = String.valueOf(val);
If your Long might be null and you don't want to get a 4-letter "null" string, you might use Objects.toString, like: String s = Objects.toString(val, null);
You reverse it using Long val = Long.parseLong(String); but in this direction you need to catch NumberFormatException
You can also do:
Long.toString(val);
A typecast does not work since String is not a primitive datatype.
I am trying to read a config file and I want to use that properties value in some algebraic operations. So I need to convert the string returned by prop.getProperty(String str) into an integer.
I have tried converting it using:
1.)
Integer value = null;
String string = getProperty(key);
if (string != null)
value = new Integer(string);
return value;
2.)
String noofdivs = prop.getProperty("NO_OF_INITIAL_DIVS");
Integer noOfInitialDivs = Integer.valueOf(noofdivs);
3.)
String xyz = prop.getProperty("NO_OF_LINES_IN_A_DIV");
Integer noOfLinesInDiv = Integer.getInteger(xyz);
but none of them is working.
Can anybody help me out with this?
int value = Integer.parseInt(string);
You can then check for a NumberFormatException to see if it was properly parsed.
Even if it could be a little bit overengineered here, you could use Apache Commons Configuration to avoid converting yourself the properties. The framework has also the advantage to throw a ConversionException if the property your are reading is not of the expected type.
Integer value = env.getProperty("name property", Integer.class);
I have a string variable which is the same as the identifier for a view.
I would like to use the R.id.xxx, but obviously I can't just replace the xxx with my string as the xxx is actually an int. What can I do to get around this?
Thanks!
Nonsense. The framework obviously discourages that approach but it is possible: just use Java reflection, e.g.,
java.lang.reflect.Field f = R.id.class.getField(name);
int id = f == null ? -1 : (Integer)f.get(null);
// now just use findViewById(id);
String s=getString(R.string.xxx);