How to Test If Json Collection Object Is Empty in Java

How to test if JSON Collection object is empty in Java

obj.length() == 0

is what I would do.

How to check if JSON object is empty in Java?

Neither of those two things are null; they are arrays. The result is exactly what you would expect.

One of your arrays is empty, the other contains a single element that is null.

If you want to know if an array is empty, you would need to get the array, then check its length.

JSONObject myJsonObject = 
new JSONObject("{\"null_object_1\":[],\"null_object_2\":[null]}");

if (myJsonObject.getJSONArray("null_object_1").length() == 0) {
...
}

Edit to clarify: An array having no elements (empty) and an array that has an element that is null are completely different things. In the case of your second array it is neither null nor empty. As I mentioned it is an array that has a single element which is null. If you are interesting in determining if that is the case, you would need to get the array then iterate through it testing each element to see if it were null and acting upon the results accordingly.

Check if Json Array is empty or contains one Json Object

You can check the data array length like this:

if(jsonArray.length() > 0) { //it means that there is a record in data attr }

Checking if a JSON key is empty before adding to constructor

org.json.JSONException: No value for description

You should check Json has. boolean has (String name)

Returns true if this object has a mapping for name.
NULL

if (items.has("description")) 
{
String description= items.getString("description"));
}

how to check if a JSONArray is empty in java?

If the array is defined in the file but is empty, like:

...
"kl":[]
...

Then getJSONArray("kl") will return an empty array, but the object is not null. Then, if you do this:

kl = c.getJSONArray("kl");
if(kl != null){
klassenID[i] = kl.getJSONObject(0).getString("id");
}

kl is not null and kl.getJSONObject(0) will throw an exception - there is no first element in the array.

Instead you can check the length(), e.g.:

kl = c.getJSONArray("kl");
if(kl != null && kl.length() > 0 ){
klassenID[i] = kl.getJSONObject(0).getString("id");
}

How to check empty array string before creating json object in java?

You can use method from is* family:

Gson gson = new GsonBuilder().create();

String[] jsons = {"[]", "[ ]", "[\r\n]", "{}", "{\"error\":\"Internal error\"}"};
for (String json : jsons) {
JsonElement root = gson.fromJson(json, JsonElement.class);
if (root.isJsonObject()) {
JsonElement error = root.getAsJsonObject().get("error");
System.out.println(error);
}
}

prints:

null
"Internal error"

There is no point to check "[]" string because between brackets could be many different white characters. JsonElement is a root type for all JSON objects and is safe to use.



Related Topics



Leave a reply



Submit