StringExample.ino 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // ArduinoJson - arduinojson.org
  2. // Copyright Benoit Blanchon 2014-2019
  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. DynamicJsonBuffer jsonBuffer;
  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. JsonObject& root = jsonBuffer.parseObject(input);
  18. // You can use a String to get an element of a JsonObject
  19. // No duplication is done.
  20. long time = root[String("time")];
  21. // You can use a String to set an element of a JsonObject
  22. // WARNING: the content of the String will be duplicated in the JsonBuffer.
  23. root[String("time")] = time;
  24. // You can get a String from a JsonObject or JsonArray:
  25. // No duplication is done, at least not in the JsonBuffer.
  26. String sensor = root["sensor"];
  27. // Unfortunately, the following doesn't work (issue #118):
  28. // sensor = root["sensor"]; // <- error "ambiguous overload for 'operator='"
  29. // As a workaround, you need to replace by:
  30. sensor = root["sensor"].as<String>();
  31. // You can set a String to a JsonObject or JsonArray:
  32. // WARNING: the content of the String will be duplicated in the JsonBuffer.
  33. root["sensor"] = sensor;
  34. // It works with RawJson too:
  35. root["sensor"] = RawJson(sensor);
  36. // You can also concatenate strings
  37. // WARNING: the content of the String will be duplicated in the JsonBuffer.
  38. root[String("sen") + "sor"] = String("gp") + "s";
  39. // You can compare the content of a JsonObject with a String
  40. if (root["sensor"] == sensor) {
  41. // ...
  42. }
  43. // Lastly, you can print the resulting JSON to a String
  44. String output;
  45. root.printTo(output);
  46. }
  47. void loop() {
  48. // not used in this example
  49. }
  50. // See also
  51. // --------
  52. //
  53. // https://arduinojson.org/ contains the documentation for all the functions
  54. // used above. It also includes an FAQ that will help you solve any problem.
  55. //
  56. // The book "Mastering ArduinoJson" contains a quick C++ course that explains
  57. // how your microcontroller stores strings in memory. On several occasions, it
  58. // shows how you can avoid String in your program.
  59. // Learn more at https://arduinojson.org/book/
  60. // Use the coupon code TWENTY for a 20% discount ❤❤❤❤❤