StringExample.ino 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright Benoit Blanchon 2014-2017
  2. // MIT License
  3. //
  4. // Arduino JSON library
  5. // https://bblanchon.github.io/ArduinoJson/
  6. // If you like this project, please add a star!
  7. #include <ArduinoJson.h>
  8. // About
  9. // -----
  10. // This example shows the different ways you can use String with ArduinoJson.
  11. // Please don't see this as an invitation to use String.
  12. // On the contrary, you should always use char[] when possible, it's much more
  13. // efficient in term of code size, speed and memory usage.
  14. void setup() {
  15. DynamicJsonBuffer jsonBuffer;
  16. // You can use a String as your JSON input.
  17. // WARNING: the content of the String will be duplicated in the JsonBuffer.
  18. String input =
  19. "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
  20. JsonObject& root = jsonBuffer.parseObject(input);
  21. // You can use a String to get an element of a JsonObject
  22. // No duplication is done.
  23. long time = root[String("time")];
  24. // You can use a String to set an element of a JsonObject
  25. // WARNING: the content of the String will be duplicated in the JsonBuffer.
  26. root[String("time")] = time;
  27. // You can get a String from a JsonObject or JsonArray:
  28. // No duplication is done, at least not in the JsonBuffer.
  29. String sensor = root["sensor"];
  30. // Unfortunately, the following doesn't work (issue #118):
  31. // sensor = root["sensor"]; // <- error "ambiguous overload for 'operator='"
  32. // As a workaround, you need to replace by:
  33. sensor = root["sensor"].as<String>();
  34. // You can set a String to a JsonObject or JsonArray:
  35. // WARNING: the content of the String will be duplicated in the JsonBuffer.
  36. root["sensor"] = sensor;
  37. // You can also concatenate strings
  38. // WARNING: the content of the String will be duplicated in the JsonBuffer.
  39. root[String("sen") + "sor"] = String("gp") + "s";
  40. // You can compare the content of a JsonObject with a String
  41. if (root["sensor"] == sensor) {
  42. // ...
  43. }
  44. // Lastly, you can print the resulting JSON to a String
  45. String output;
  46. root.printTo(output);
  47. }
  48. void loop() {
  49. // not used in this example
  50. }