Description

Casts JsonDocument to the specified type.

Unlike JsonDocument::to<T>(), this function doesn’t change the content of the JsonDocument.

Signature

bool               as<bool>() const;

float              as<float>() const;
double             as<double>() const;

signed char        as<signed char>() const;
unsigned char      as<unsigned char>() const;
signed int         as<signed int>() const;
unsigned int       as<unsigned int>() const;
signed short       as<signed short>() const;
unsigned short     as<unsigned short>() const;
signed long        as<signed long>() const;
unsigned long      as<unsigned long>() const;
unsigned long long as<unsigned long long>() const;   // ⚠️ may require ARDUINOJSON_USE_LONG_LONG
signed long long   as<signed long long>() const;     // ⚠️ may require ARDUINOJSON_USE_LONG_LONG
signed __int64     as<signed __int64>() const;       // ⚠️ may require ARDUINOJSON_USE_INT64
unsigned __int64   as<unsigned __int64>() const;     // ⚠️ may require ARDUINOJSON_USE_INT64

const char*        as<char*>() const;  // ⚠️ deprecated since 6.18
const char*        as<const char*>() const;
String             as<String>() const;
std::string        as<std::string>() const;

JsonArray          as<JsonArray>();
JsonObject         as<JsonObject>();
JsonVariant        as<JsonVariant>();

JsonArrayConst     as<JsonArrayConst>() const;
JsonObjectConst    as<JsonObjectConst>() const;
JsonVariantConst   as<JsonVariantConst>() const;

TEnum              as<TEnum>() const;  // 🆕 alias of as<int>() (added in 6.15.2)
T                  as<T>() const;      // 🆕 calls user-defined converter (added in 6.18.0)

Return value

This function returns a reference to the root of the JsonDocument.

If the actual type of the root doesn’t match the requested type, this function returns a null reference. For example, suppose the JsonDocument is an array, if you call JsonDocument::as<JsonObject>(), it will return a null JsonObject.

Integer overflows

JsonDocument::as<T>() is aware of integer overflows and only returns a value if it can fit in the specified type.

For example, if the value contains 512, as<char>() returns 0, but as<int>() returns 512.

This feature was added in ArduinoJson 6.10.0

User-defined types 🆕

JsonDocument::as<T>() supports user-defined types by calling convertFromJson(). For example, to support tm, you must define:

void convertFromJson(JsonVariantConst src, tm& dst) {
  strptime(src.as<const char*>(), "%FT%TZ", &dst);
}

This feature was added in ArduinoJson 6.18.0, see article for details.

Example

DynamicJsonDocument doc(1024);
deserializeJson(doc, "{\"key\":\"value\")");

// get the JsonObject in the JsonDocument
JsonObject root = doc.as<JsonObject>();

// get the value in the JsonObject
const char* value = root["key"];

See also

 X online