2

I dont understand what is happening in my application. I'm sending PUT request with updates from Angular project to java api. I have a method that validates query parameters from the put request, the method looks like this:

private JsonObject validateRequestBody(JsonElement requestBody) {
    if (!(requestBody instanceof JsonObject)) {
        throw new IllegalArgumentException("Request body cannot be case to JSON object");
    }
    JsonObject bodyObj = requestBody.getAsJsonObject();
    System.out.println(bodyObj.get("entityIri").equals(null));
    if (bodyObj.get("entityIri") == null) {
        System.out.println("null");
        throw new IllegalArgumentException("Request body must contain entity IRI");
    }
    return bodyObj;
}

As you can see, I'm just trying to check if the enityIri paramter is equal to null. To test it, Im sending null as entityIri from Angular project. I tried to compare them with equal method and with ==, but in both cases the output is always false. Could someone explain me why they are not equal? Is it because I'm passing it to JsonObject? I attach a screenshot from debugging (I cut out irrelevant parts).

jhamon
  • 3,603
  • 4
  • 26
  • 37
McLovin
  • 91
  • 2
  • 10
  • 1
    Does this answer your question? [How to compare null value from the JsonObject in java](https://stackoverflow.com/questions/8802236/how-to-compare-null-value-from-the-jsonobject-in-java) – Simon Crane Jan 10 '20 at 10:20
  • `bodyObj.get()` will return instance of `JsonObject` and it is not `null`, you can call `getAsString()` or whatever to perform such verification – Vault23 Jan 10 '20 at 10:20
  • I tried comparing `bodyObj.get("entityIri")` to `"null"`, but it was also false. Besides in the screenshot, its visible that during debugging, the value of `bodyObj.get("entityIri")` is null, not a string because it doesnt have quotation marks – McLovin Jan 10 '20 at 10:20

1 Answers1

6

Try to use isJsonNull method:

provides check for verifying if this element represents a null value or not.

if (bodyObj.get("entityIri").isJsonNull()) {
    ...
}

Of course, you need to check whether bodyObj.get("entityIri") is not null before. I did not add it statement to make statement clear.

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
  • 1
    Which of course will throw `NullPointerException` if `entityIri` is missing. – Andreas Jan 10 '20 at 10:28
  • @Andreas, I just wanted to make it clear how to use it. But, of course, you are right. I added extra comment that checking `null` is good idea. – Michał Ziober Jan 10 '20 at 10:32