Description

JsonVariant is a reference to a value in a JsonDocument. It supports all types allowed by JSON:

  • boolean
  • integer
  • floating point
  • string
  • array
  • object

JsonVariant doesn’t own the value: it only points to it. The value belongs to the JsonDocument.

Constness

You’ll see that most member functions of JsonVariant are const. These methods do not modify the instance, but they may alter the value pointed by the JsonVariant.

As we said, a JsonVariant is a reference; the const-ness of the member functions refers to the reference object, not to the value.

ArduinoJson also supports a read-only reference type named JsonVariantConst. It’s similar to JsonVariant, except it doesn’t allow modifying the value.

Example

Create a variant and serialize it

// allocate the memory for the document
DynamicJsonDocument doc(1024);

// 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(1024);

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

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

Member functions

JsonVariant also supports the comparison operators ==, !=, <, <=, >, and >=.

See also

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