ProgmemExample.ino 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // ArduinoJson - https://arduinojson.org
  2. // Copyright Benoit Blanchon 2014-2021
  3. // MIT License
  4. //
  5. // This example shows the different ways you can use Flash strings with
  6. // ArduinoJson.
  7. //
  8. // Use Flash strings sparingly, because ArduinoJson duplicates them in the
  9. // JsonDocument. Prefer plain old char*, as they are more efficient in term of
  10. // code size, speed, and memory usage.
  11. //
  12. // https://arduinojson.org/v6/example/progmem/
  13. #include <ArduinoJson.h>
  14. void setup() {
  15. DynamicJsonDocument doc(1024);
  16. // You can use a Flash String as your JSON input.
  17. // WARNING: the strings in the input will be duplicated in the JsonDocument.
  18. deserializeJson(doc, F("{\"sensor\":\"gps\",\"time\":1351824120,"
  19. "\"data\":[48.756080,2.302038]}"));
  20. JsonObject obj = doc.as<JsonObject>();
  21. // You can use a Flash String to get an element of a JsonObject
  22. // No duplication is done.
  23. long time = obj[F("time")];
  24. // You can use a Flash String to set an element of a JsonObject
  25. // WARNING: the content of the Flash String will be duplicated in the
  26. // JsonDocument.
  27. obj[F("time")] = time;
  28. // You can set a Flash String to a JsonObject or JsonArray:
  29. // WARNING: the content of the Flash String will be duplicated in the
  30. // JsonDocument.
  31. obj["sensor"] = F("gps");
  32. // It works with serialized() too:
  33. obj["sensor"] = serialized(F("\"gps\""));
  34. obj["sensor"] = serialized(F("\xA3gps"), 3);
  35. // You can compare the content of a JsonVariant to a Flash String
  36. if (obj["sensor"] == F("gps")) {
  37. // ...
  38. }
  39. }
  40. void loop() {
  41. // not used in this example
  42. }
  43. // See also
  44. // --------
  45. //
  46. // https://arduinojson.org/ contains the documentation for all the functions
  47. // used above. It also includes an FAQ that will help you solve any memory
  48. // problem.
  49. //
  50. // The book "Mastering ArduinoJson" contains a quick C++ course that explains
  51. // how your microcontroller stores strings in memory. It also tells why you
  52. // should not abuse Flash strings with ArduinoJson.
  53. // Learn more at https://arduinojson.org/book/
  54. // Use the coupon code TWENTY for a 20% discount ❤❤❤❤❤