MsgPackParserExample.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // ArduinoJson - arduinojson.org
  2. // Copyright Benoit Blanchon 2014-2020
  3. // MIT License
  4. //
  5. // This example shows how to generate a JSON document with ArduinoJson.
  6. #include <iostream>
  7. #include "ArduinoJson.h"
  8. int main() {
  9. // Allocate the JSON document
  10. //
  11. // Inside the brackets, 300 is the size of the memory pool in bytes.
  12. // Don't forget to change this value to match your JSON document.
  13. // Use arduinojson.org/assistant to compute the capacity.
  14. StaticJsonDocument<300> doc;
  15. // StaticJsonObject allocates memory on the stack, it can be
  16. // replaced by DynamicJsonObject which allocates in the heap.
  17. //
  18. // DynamicJsonObject doc(200);
  19. // MessagePack input string.
  20. //
  21. // It's better to use a char[] as shown here.
  22. // If you use a const char* or a String, ArduinoJson will
  23. // have to make a copy of the input in the JsonBuffer.
  24. uint8_t input[] = {131, 166, 115, 101, 110, 115, 111, 114, 163, 103, 112, 115,
  25. 164, 116, 105, 109, 101, 206, 80, 147, 50, 248, 164, 100,
  26. 97, 116, 97, 146, 203, 64, 72, 96, 199, 58, 188, 148,
  27. 112, 203, 64, 2, 106, 146, 230, 33, 49, 169};
  28. // This MessagePack document contains:
  29. // {
  30. // "sensor": "gps",
  31. // "time": 1351824120,
  32. // "data": [48.75608, 2.302038]
  33. // }
  34. // doc of the object tree.
  35. //
  36. // It's a reference to the JsonObject, the actual bytes are inside the
  37. // JsonBuffer with all the other nodes of the object tree.
  38. // Memory is freed when jsonBuffer goes out of scope.
  39. DeserializationError error = deserializeMsgPack(doc, input);
  40. // Test if parsing succeeds.
  41. if (error) {
  42. std::cerr << "deserializeMsgPack() failed: " << error.c_str() << std::endl;
  43. return 1;
  44. }
  45. // Fetch values.
  46. //
  47. // Most of the time, you can rely on the implicit casts.
  48. // In other case, you can do doc["time"].as<long>();
  49. const char* sensor = doc["sensor"];
  50. long time = doc["time"];
  51. double latitude = doc["data"][0];
  52. double longitude = doc["data"][1];
  53. // Print values.
  54. std::cout << sensor << std::endl;
  55. std::cout << time << std::endl;
  56. std::cout << latitude << std::endl;
  57. std::cout << longitude << std::endl;
  58. return 0;
  59. }