JsonParserExample.ino 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. void setup() {
  9. Serial.begin(9600);
  10. while (!Serial) {
  11. // wait serial port initialization
  12. }
  13. // Memory pool for JSON object tree.
  14. //
  15. // Inside the brackets, 200 is the size of the pool in bytes,
  16. // If the JSON object is more complex, you need to increase that value.
  17. // See https://bblanchon.github.io/ArduinoJson/assistant/
  18. StaticJsonBuffer<200> jsonBuffer;
  19. // StaticJsonBuffer allocates memory on the stack, it can be
  20. // replaced by DynamicJsonBuffer which allocates in the heap.
  21. //
  22. // DynamicJsonBuffer jsonBuffer(200);
  23. // JSON input string.
  24. //
  25. // It's better to use a char[] as shown here.
  26. // If you use a const char* or a String, ArduinoJson will
  27. // have to make a copy of the input in the JsonBuffer.
  28. char json[] =
  29. "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
  30. // Root of the object tree.
  31. //
  32. // It's a reference to the JsonObject, the actual bytes are inside the
  33. // JsonBuffer with all the other nodes of the object tree.
  34. // Memory is freed when jsonBuffer goes out of scope.
  35. JsonObject& root = jsonBuffer.parseObject(json);
  36. // Test if parsing succeeds.
  37. if (!root.success()) {
  38. Serial.println("parseObject() failed");
  39. return;
  40. }
  41. // Fetch values.
  42. //
  43. // Most of the time, you can rely on the implicit casts.
  44. // In other case, you can do root["time"].as<long>();
  45. const char* sensor = root["sensor"];
  46. long time = root["time"];
  47. double latitude = root["data"][0];
  48. double longitude = root["data"][1];
  49. // Print values.
  50. Serial.println(sensor);
  51. Serial.println(time);
  52. Serial.println(latitude, 6);
  53. Serial.println(longitude, 6);
  54. }
  55. void loop() {
  56. // not used in this example
  57. }