Description

A variant can hold any type of values allowed by JSON:

  • a boolean
  • an integer
  • a floating point value
  • a string
  • an array
  • an object

A JsonVariant is a reference to this value, but a JsonDocument owns the data.

Because the JsonVariant is a just reference, you need a JsonDocument to create a JSON object. See the example below.

Example

Create a variant and serialize it

// allocate the memory for the document
DynamicJsonDocument doc;

// create a variant
JsonVariant variant = doc.to<JsonVariant>();
variant.set(42);

// serialize the object and send the result to Serial
serializeJson(doc, Serial);

Deserialize a variant

// allocate the memory for the document
DynamicJsonDocument doc;

// deserialize the object
char json[] = "42";
deserializeJson(doc, json);

// extract the data
JsonVariant variant = doc.as<JsonVariant>();
int value = variant.as<int>();

Member functions

See also