Description

JsonDocument::set() replaces the root value of the JsonDocument.

Signatures

bool set(bool value) const;

bool set(float value) const;
bool set(double value) const;

bool set(signed char value) const;
bool set(signed long value) const;
bool set(signed int value) const;
bool set(signed short value) const;
bool set(unsigned char value) const;
bool set(unsigned long value) const;
bool set(unsigned int value) const;
bool set(unsigned short value) const;

bool set(char *value) const;                       // stores a copy
bool set(const char *value) const;                 // stores a pointer ⚠️
bool set(const __FlashStringHelper *value) const;  // stores a copy

bool set(const String &value) const;       // stores a copy
bool set(const std::string &value) const;  // stores a copy
bool set(const Printable &value) const;    // stores a copy
bool set(std::string_view value) const;    // stores a copy

bool set(JsonArray array) const;         // stores a deep copy
bool set(JsonObject object) const;       // stores a deep copy
bool set(JsonVariant variant) const;     // stores a deep copy
bool set(const JsonVariant &doc) const;  // stores a deep copy

bool set(TEnum value) const;  // alias of set(int)
bool set(T value) const;      // calls user-defined function

Arguments

value: the new value of the document, it can be any type supported by ArduinoJson or a user-defined type if you define custom converters.

All types are stored by copy, except const char* which is stored by pointer.

Return value

JsonDocument::set() returns a bool that tells whether the operation was successful or not:

  • true if the value operation was successful.
  • false if there was not enough room in the JsonDocument.

User-defined types

JsonDocument::set() supports user-defined types by calling convertToJson(). For example, to support tm, you must define:

bool convertToJson(const tm& src, JsonVariant dst) {
  char buf[32];
  strftime(buf, sizeof(buf), "%FT%TZ", &src);
  return dst.set(buf);
}

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

Example

DynamicJsonDocument doc(2048);
doc.set("hello world")
serializeJson(doc, Serial);

The above program produces the following output:

"hello world"

See also

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