StringExample.ino 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // ArduinoJson - arduinojson.org
  2. // Copyright Benoit Blanchon 2014-2018
  3. // MIT License
  4. //
  5. // This example shows the different ways you can use String with ArduinoJson.
  6. //
  7. // Use String objects sparingly, because ArduinoJson duplicates them in the
  8. // JsonBuffer. Prefer plain old char[], as they are more efficient in term of
  9. // code size, speed, and memory usage.
  10. #include <ArduinoJson.h>
  11. void setup() {
  12. DynamicJsonDocument doc;
  13. // You can use a String as your JSON input.
  14. // WARNING: the content of the String will be duplicated in the JsonBuffer.
  15. String input =
  16. "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
  17. deserializeJson(doc, input);
  18. JsonObject obj = doc.as<JsonObject>();
  19. // You can use a String to get an element of a JsonObject
  20. // No duplication is done.
  21. long time = obj[String("time")];
  22. // You can use a String to set an element of a JsonObject
  23. // WARNING: the content of the String will be duplicated in the JsonBuffer.
  24. obj[String("time")] = time;
  25. // You can get a String from a JsonObject or JsonArray:
  26. // No duplication is done, at least not in the JsonBuffer.
  27. String sensor = obj["sensor"];
  28. // Unfortunately, the following doesn't work (issue #118):
  29. // sensor = obj["sensor"]; // <- error "ambiguous overload for 'operator='"
  30. // As a workaround, you need to replace by:
  31. sensor = obj["sensor"].as<String>();
  32. // You can set a String to a JsonObject or JsonArray:
  33. // WARNING: the content of the String will be duplicated in the JsonBuffer.
  34. obj["sensor"] = sensor;
  35. // It works with serialized() too:
  36. obj["sensor"] = serialized(sensor);
  37. // You can also concatenate strings
  38. // WARNING: the content of the String will be duplicated in the JsonBuffer.
  39. obj[String("sen") + "sor"] = String("gp") + "s";
  40. // You can compare the content of a JsonObject with a String
  41. if (obj["sensor"] == sensor) {
  42. // ...
  43. }
  44. // Lastly, you can print the resulting JSON to a String
  45. String output;
  46. serializeJson(doc, output);
  47. }
  48. void loop() {
  49. // not used in this example
  50. }
  51. // Visit https://arduinojson.org/v6/example/string/ for more.