How to check if JSONArray Element is null - java

I can't figure out how to determine is an element that lives inside a json array is null. To check if the jsonObject itself is null, you simply use:
jsonObject.isNullObject();
But when the object is an array and I want to check if one of the elements of that array is null, this does not work:
jsonArray.get(i).get("valueThatIsNull") == null;
There is also no isNull method available on elements of an array. How do I check if values inside a jsonarray are null? It might help to know that I am passing over a null object from javascript. Maybe null does not mean the same thing in java when it is passed from javascript in json format, but I have also tried putting parentheses around the null and it still does not work.
I am posting some actual source code to help make this clearer. The jsonObject is a part of the jsonArray and the object has multiple values because it iself is an object.
JSONObject mapItem = jsonArray.getJSONObject(i);
int id = mapItem.has("id") ? mapItem.getInt("id") : -1;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = null;
Date sqlDate = null;
if(mapItem.has("date")) {
String dateStr = mapItem.getString("date");
if(!dateStr.equals("null")) {
date = dateFormat.parse(mapItem.getString("date").substring(0, 10)); //Convert javascript date string to java.
sqlDate = new Date(date.getTime());
}

Try .isNull():
For your example:
if(!mapItem.isNull("date")) {
//Value is not null
}
However, to answer the title of this question, "how to tell if a JSONArray element is null", use .equals()
So, to check if index 1 is null:
if (!jsonArray.get(1).equals(null)) {
//jsonArray[1] is not null
}

I guess json passes null values as strings, so you can't check null as a java element. Instead treat the null value as a string as check this way:
if(!mapItem.getString("date").equals("null")) {
//Value is not null
}
I have updated the code snippet in the original question to a working version.

try JSONArray's method
public boolean isNull (int index)
In fact, it uses "null" string comparing to the content
JSONObject.NULL.equals(this.opt(index));

Related

Compare the key of a JSON Object to a String

I am trying to compare the key of a JSON Object to a String to assess whether or not my JSON Object contains the specified value at that key before continue processing.
Here is a sample of the String .
{'type':'Layout','subType':'REPEATGRID','pgRef':'.pySections(1).pySectionBody(1).pyTable.pyRows(1).pyCells(3).pySections(1)'}
Here is the code I used to perform the evaluation. Let's assume the String above is store in a variable str
jsonString = str.replaceAll("\'", "\"");
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(jsonString);
System.out.println((String) jsonObject.get("subType") == "REPEATGRID");
The code above returns false while the statement System.out.println((String) jsonObject.get("subType")); returns REPEATGRID
Why is the evaluation returning false?
How can I properly evaluate this situation?
PS: I am using org.json.simple library.
try to use equals() instead of ==
System.out.println((String) jsonObject.get("subType").equals("REPEATGRID"));
Further more,to aovid NullPointerException,you can improve as above:
System.out.println("REPEATGRID".equals((String) jsonObject.get("subType")));

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

Why JsonNull in GSON?

The docs say the JsonObject#get method returns null if no such member exists. That's not accurate; sometimes a JsonNull object is returned instead of null.
What is the idiom for checking whether a particular field exists in GSON? I wish to avoid this clunky style:
jsonElement = jsonObject.get("optional_field");
if (jsonElement != null && !jsonElement.isJsonNull()) {
s = jsonElement .getAsString();
}
Why did GSON use JsonNull instead of null?
There is an answer for what are the differences between null and JsonNull. In my question above, I'm looking for the reasons why.
Gson, presumably, wanted to model the difference between the absence of a value and the presence of the JSON value null in the JSON. For example, there's a difference between these two JSON snippets
{}
{"key":null}
your application might consider them the same, but the JSON format doesn't.
Calling
JsonObject jsonObject = new JsonObject(); // {}
jsonObject.get("key");
returns the Java value null because no member exists with that name.
Calling
JsonObject jsonObject = new JsonObject();
jsonObject.add("key", JsonNull.INSTANCE /* or even null */); // {"key":null}
jsonObject.get("key");
returns an instance of type JsonNull (the singleton referenced by JsonNull.INSTANCE) because a member does exist with that name and its value is JSON null, represented by the JsonNull value.
I know question is not asking for a solution, but I came here looking for one. So I will post it in case someone else needs it.
Below Kotlin extension code saves the trouble of checking for null and isJsonNull separately for each element
import com.google.gson.JsonElement
import com.google.gson.JsonObject
fun JsonObject.getNullable(key: String): JsonElement? {
val value: JsonElement = this.get(key) ?: return null
if (value.isJsonNull) {
return null
}
return value
}
and instead of calling like this
jsonObject.get("name")
you call like this
jsonObject.getNullable("name")
Works particularly great in nested structures. Your code eventually would look like this
val name = jsonObject.getNullable("owner")?.asJsonObject?.
getNullable("personDetails")?.asJsonObject?.
getNullable("name")
?: ""

GSON: Custom deserialiser throws java.lang.UnsupportedOperationException: JsonNull [duplicate]

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

How to check if a JSON key exists?

So, I get some JSON values from the server but I don't know if there will be a particular field or not.
So like:
{ "regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited"
}
And sometimes, there will be an extra field like:
{ "regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited",
"club":"somevalue"
}
I would like to check if the field named "club" exists so that at parsing I won't get
org.json.JSONException: No value for club
JSONObject class has a method named "has":
http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)
Returns true if this object has a mapping for name. The mapping may be NULL.
You can check this way where 'HAS' - Returns true if this object has a mapping for name. The mapping may be NULL.
if (json.has("status")) {
String status = json.getString("status"));
}
if (json.has("club")) {
String club = json.getString("club"));
}
You can also check using 'isNull' - Returns true if this object has no
mapping for name or if it has a mapping whose value is NULL.
if (!json.isNull("club"))
String club = json.getString("club"));
you could JSONObject#has, providing the key as input and check if the method returns true or false. You could also
use optString instead of getString:
Returns the value mapped by name if it exists, coercing it if
necessary. Returns the empty string if no such mapping exists
just before read key check it like before read
JSONObject json_obj=new JSONObject(yourjsonstr);
if(!json_obj.isNull("club"))
{
//it's contain value to be read operation
}
else
{
//it's not contain key club or isnull so do this operation here
}
isNull function definition
Returns true if this object has no mapping for name or
if it has a mapping whose value is NULL.
official documentation below link for isNull function
http://developer.android.com/reference/org/json/JSONObject.html#isNull(java.lang.String)
You can use has
public boolean has(String key)
Determine if the JSONObject contains a specific key.
Example
JSONObject JsonObj = new JSONObject(Your_API_STRING); //JSONObject is an unordered collection of name/value pairs
if (JsonObj.has("address")) {
//Checking address Key Present or not
String get_address = JsonObj .getString("address"); // Present Key
}
else {
//Do Your Staff
}
A better way, instead of using a conditional like:
if (json.has("club")) {
String club = json.getString("club"));
}
is to simply use the existing method optString(), like this:
String club = json.optString("club);
the optString("key") method will return an empty String if the key does not exist and won't, therefore, throw you an exception.
Try this:
let json=yourJson
if(json.hasOwnProperty(yourKey)){
value=json[yourKey]
}
Json has a method called containsKey().
You can use it to check if a certain key is contained in the Json set.
File jsonInputFile = new File("jsonFile.json");
InputStream is = new FileInputStream(jsonInputFile);
JsonReader reader = Json.createReader(is);
JsonObject frameObj = reader.readObject();
reader.close();
if frameObj.containsKey("person") {
//Do stuff
}
Try this
if(!jsonObj.isNull("club")){
jsonObj.getString("club");
}
I used hasOwnProperty('club')
var myobj = { "regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited"
};
if ( myobj.hasOwnProperty("club"))
// do something with club (will be false with above data)
var data = myobj.club;
if ( myobj.hasOwnProperty("status"))
// do something with the status field. (will be true with above ..)
var data = myobj.status;
works in all current browsers.
You can try this to check wether the key exists or not:
JSONObject object = new JSONObject(jsonfile);
if (object.containskey("key")) {
object.get("key");
//etc. etc.
}
I am just adding another thing, In case you just want to check whether anything is created in JSONObject or not you can use length(), because by default when JSONObject is initialized and no key is inserted, it just has empty braces {} and using has(String key) doesn't make any sense.
So you can directly write if (jsonObject.length() > 0) and do your things.
Happy learning!
You can use the JsonNode#hasNonNull(String fieldName), it mix the has method and the verification if it is a null value or not

Categories

Resources