ARDUINOJSON_ENABLE_ARDUINO_STRING
Description
The macro ARDUINOJSON_ENABLE_ARDUINO_STRING
enables the support of the String
class in the library.
The default is 1
of ARDUINO
is defined, 0
otherwise.
In other words, ArduinoJson supports the String
class as soon as you work in an Arduino-compatible environment.
How to force the value?
If you need to force the support of String
, add this at the top of your program:
#define ARDUINOJSON_ENABLE_ARDUINO_STRING 1
#include <ArduinoJson.h>
On the other hand, if you need to disable String
, do:
#define ARDUINOJSON_ENABLE_ARDUINO_STRING 0
#include <ArduinoJson.h>
Only 0
and 1
are valid. Any other value (like false
or true
) will produce a compilation error.
Where ArduinoJson supports the String
class?
Once enabled, you can use a String
in many places.
-
You can use a
String
as your JSON input// WARNING: ArduinoJson duplicates the String in the JsonDocument String input = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}"; deserializeJson(doc, input);
-
You can use a
String
to get an element of aJsonObject
long time = doc[String("time")];
-
You can use a
String
to set an element of aJsonObject
// WARNING: ArduinoJson duplicates the String in the JsonDocument doc[String("time")] = time;
-
You can get a
String
from aJsonObject
orJsonArray
String sensor = doc["sensor"];
-
You use a
String
as a value for aJsonObject
orJsonArray
// WARNING: ArduinoJson duplicates the String in the JsonDocument doc["sensor"] = sensor;
-
You can also concatenate strings
// WARNING: ArduinoJson duplicates the String in the JsonDocument doc[String("sen") + "sor"] = String("gp") + "s";
-
You can compare the content of a
JsonObject
with aString
if (doc["sensor"] == sensor) { // ... }
-
You can print the resulting JSON to a
String
String output; serializeJson(doc, output);
The one place where it doesn’t work ⚠️
Unfortunately, the following doesn’t work (issue #118):
String sensor = "something";
sensor = doc["sensor"]; // <- error "ambiguous overload for 'operator='"
This line is ambiguous because the compiler cannot tell which constructor of String
to call.
Is it the one taking a const char*
, an int
, or a float
?
To solve this ambiguity, you must explicitly cast the JsonVariant
to a String
:
sensor = doc["sensor"].as<String>();