0

I have an JSON object like this:

{ "foo": null }

How do I check if the value of foo is a literal null. I found the function JsonObject::isNull() but that apparently is for

testing whether the JsonObject points to an object or not

That is not what I want my code to check, but I couldn't find a solution to this problem.

Wouterr
  • 516
  • 7
  • 16
  • 1
    The docs suggest https://arduinojson.org/v6/api/jsonvariant/isnull/ – UnholySheep Sep 29 '21 at 19:00
  • The documentation does suggest that `JsonVariant::isNull` is checking if the `JsonVariant` itself is a valid pointer into a `JsonDocument`, rather than whether or not the pointed-to JSON value is `null` instead of something else. – Nathan Pierson Sep 29 '21 at 19:06
  • 2
    @NathanPierson, There's an example on the page where it returns true for a null value as desired. It seems you still have to do something like `containsKey` manually to differentiate, though. – chris Sep 29 '21 at 19:09
  • Ah, thank you all. The `isNull` in combination with the `containsKey` seems to work. To **serialize** a null value I found that `doc["foo"] = nullptr` works. – Wouterr Oct 03 '21 at 10:59

1 Answers1

1

According to the doc: https://arduinojson.org/v6/issues/cannot-use-null/

  • If c++11 is available (which has nullptr), you can check if the json object's value is null or not like so:
if (!doc["foo"]) {}

or

if (doc["foo"] == nullptr) {}
  • If c++11 is not available, you can use the isNull() method:
if (doc["foo"].isNull()) {}
Nam Vu
  • 1,727
  • 1
  • 11
  • 24
  • 1
    Just note that using `doc["foo"].isNull()` does not differentiate between the document not containing a `"foo"` value at all versus having a `"foo"` value that is `null`. If you want to differentiate, use `doc.containsKey("foo")`. This library doesn't really seem to handle `null` very well. Most JSON libraries I've worked with represent `null` as its own type that can be handled specifically. This library doesn't seem to do that. – Remy Lebeau Sep 29 '21 at 20:19