StringExample.ino 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // ArduinoJson - arduinojson.org
  2. // Copyright Benoit Blanchon 2014-2017
  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. // You can also concatenate strings
  35. // WARNING: the content of the String will be duplicated in the JsonBuffer.
  36. root[String("sen") + "sor"] = String("gp") + "s";
  37. // You can compare the content of a JsonObject with a String
  38. if (root["sensor"] == sensor) {
  39. // ...
  40. }
  41. // Lastly, you can print the resulting JSON to a String
  42. String output;
  43. root.printTo(output);
  44. }
  45. void loop() {
  46. // not used in this example
  47. }
  48. // See also
  49. // --------
  50. //
  51. // The website arduinojson.org contains the documentation for all the functions
  52. // used above. It also includes an FAQ that will help you solve any problem.
  53. // Please check it out at: https://arduinojson.org/
  54. //
  55. // The book "Mastering ArduinoJson" contains a quick C++ course that explains
  56. // how your microcontroller stores strings in memory. On several occasions, it
  57. // shows how you can avoid String in your program.
  58. // Please check it out at: https://leanpub.com/arduinojson/