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.
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.
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 a JsonObject
long time = doc[String("time")];
You can use a String
to set an element of a JsonObject
// WARNING: ArduinoJson duplicates the String in the JsonDocument
doc[String("time")] = time;
You can get a String
from a JsonObject
or JsonArray
String sensor = doc["sensor"];
You use a String
as a value for a JsonObject
or JsonArray
// 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 a String
if (doc["sensor"] == sensor) {
// ...
}
You can print the resulting JSON to a String
String output;
serializeJson(doc, output);
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>();
See also
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4