Description

JsonVariantConst::is<T>() tests if the variant is currently holding a value of type T.

If you want to test that the value exists regardless of its type, you can use is<JsonVariantConst>().

Signatures

bool is<bool>() const;

bool is<float>() const;
bool is<double>() const;

bool is<signed char>() const;
bool is<unsigned char>() const;
bool is<signed int>() const;
bool is<unsigned int>() const;
bool is<signed short>() const;
bool is<unsigned short>() const;
bool is<signed long>() const;
bool is<unsigned long>() const;
bool is<unsigned long long>() const;   // ⚠️ may require ARDUINOJSON_USE_LONG_LONG
bool is<signed long long>() const;     // ⚠️ may require ARDUINOJSON_USE_LONG_LONG

bool is<const char*>() const;

bool is<JsonArray>() const;    // ⚠️ always returns false
bool is<JsonObject>() const;   // ⚠️ always returns false
bool is<JsonVariant>() const;  // ⚠️ always returns false

bool is<JsonArrayConst>() const;
bool is<JsonObjectConst>() const;
bool is<JsonVariantConst>() const;

bool is<TEnum>() const; // alias of as<int>()
bool is<T>() const;     // calls user-defined function

Return value

  • true if the variant is currently holding a value of type T,
  • false if not

JSON types vs. C++ types

Different C++ types can store the same JSON value, so is<T>() can return true for several Ts. For example, is<float>() always returns the same value as is<double>() .

The table below gives the correspondence between the JSON type and the C++ types:

JSON type T
Floating point float, double
Integer int, short, long, long long
String const char*, char*
Boolean bool
Array JsonArray
Object JsonObject

Caution: is<float>() and is<double>() return true for integers too.

Integer overflows

JsonVariantConst::is<T>() is aware of integer overflows and only returns true if the specified type can store the value.

For example if the variant contains 512, is<char>() returns false, but is<int>() return true.

User-defined types

JsonVariantConst::is<T>() supports user-defined types by calling canConvertFromJson(). For example, to support an hypothetical Complex class, we could write:

bool canConvertFromJson(JsonVariantConst src, const Complex&) {
  return src["real"].is<double>() && src["imag"].is<double>();
}

The second parameter of canConvertFromJson() is required to trigger ADL but must not be used by the function.

See also

Global warming stripes by Professor Ed Hawkins (University of Reading)