Description

JsonVariant::to<T>() clears the content of the variant and changes its type to T.

It has no effect if the JsonVariant is unbound.

Signatures

JsonArray  to<JsonArray>() const;
JsonObject to<JsonObject>() const;

Return value

A reference to the new value of the variant.

as<T>() vs to<T>()

JsonVariant::as<T>() and JsonVariant::to<T>() look similar but are very different: the former reads the value, whereas the latter changes the reference.

Suppose the JsonVariant refers to an object:

JsonVariant::to<T>() allows creating an empty object or an empty array, and it’s probably its only legitimate use. Calling JsonVariant::to<T>() with a T other than JsonArray or JsonObject works but has no practical use.

JsonVariant::as<T>(), on the other hand, allows solving situations where implicit casts don’t work; for example, when you call a function with several matching overloads (like Serial::print()) or when you use type deduction with the auto keyword (see example below).

Remark that JsonVariantConst, which is a read-only version of JsonVariant, supports as<T>() but not to<T>().

Example

void fillConfig(JsonVariant variant) {
  JsonObject config = variant.to<JsonObject>();
  config["host"] = "127.0.0.1";
  config["port"] = 80;
}

See also