Description

This example shows the different ways you can use Flash strings with ArduinoJson.

Use Flash strings sparingly, because ArduinoJson duplicates them in the JsonObject. Prefer plain old char*, as they are more efficient in term of code size, speed, and memory usage.

Source code

#include <ArduinoJson.h>

void setup() {
  DynamicJsonDocument doc(1024);

  // You can use a Flash String as your JSON input.
  // WARNING: the strings in the input  will be duplicated in the JsonDocument.
  deserializeJson(doc, F("{\"sensor\":\"gps\",\"time\":1351824120,"
                         "\"data\":[48.756080,2.302038]}"));
  JsonObject obj = doc.as<JsonObject>();

  // You can use a Flash String to get an element of a JsonObject
  // No duplication is done.
  long time = obj[F("time")];

  // You can use a Flash String to set an element of a JsonObject
  // WARNING: the content of the Flash String will be duplicated in the
  // JsonDocument.
  obj[F("time")] = time;

  // You can set a Flash String to a JsonObject or JsonArray:
  // WARNING: the content of the Flash String will be duplicated in the
  // JsonDocument.
  obj["sensor"] = F("gps");

  // It works with serialized() too:
  obj["sensor"] = serialized(F("\"gps\""));
  obj["sensor"] = serialized(F("\xA3gps"), 3);

  // You can compare the content of a JsonVariant to a Flash String
  if (obj["sensor"] == F("gps")) {
    // ...
  }
}

void loop() {
  // not used in this example
}

Classes used in this example

Functions used in this example

Keep learning

Mastering ArduinoJson

Mastering ArduinoJson begins with a quick C++ course that explains how your microcontroller stores strings in memory, so you can perfectly understand what happens behind the scenes.

The chapter “Inside ArduinoJson” explains what a JsonDocument is and why it is essential for the performance of the library. This chapter also describes how StaticJsonDocument and DynamicJsonDocument work, and how to choose between them.

 X online