StringExample.ino 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Copyright Benoit Blanchon 2014-2016
  2. // MIT License
  3. //
  4. // Arduino JSON library
  5. // https://github.com/bblanchon/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[String("sensor")];
  30. // You can set a String to a JsonObject or JsonArray:
  31. // WARNING: the content of the String will be duplicated in the JsonBuffer.
  32. root["sensor"] = sensor;
  33. // You can also concatenate strings
  34. // WARNING: the content of the String will be duplicated in the JsonBuffer.
  35. root[String("sen") + "sor"] = String("gp") + "s";
  36. // Lastly, you can print the resulting JSON to a String
  37. String output;
  38. root.printTo(output);
  39. }
  40. void loop() {
  41. // not used in this example
  42. }