JsonVariant::is<T>()
Description
JsonVariant::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<JsonVariant>()
.
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;
bool is<JsonObject>() const;
bool is<JsonVariant>() const;
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 typeT
,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 T
s. 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
JsonVariant::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
JsonVariant::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.
Example
variant.set(42);
variant.is<int>(); // true
variant.is<double>(); // true
variant.is<const char*>(); // false
variant.is<JsonArray>(); // false