MsgPackParserExample.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // ArduinoJson - https://arduinojson.org
  2. // Copyright © 2014-2023, Benoit BLANCHON
  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 parentheses, 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 https://arduinojson.org/assistant to compute the capacity.
  14. JsonDocument doc(300);
  15. // MessagePack input string.
  16. //
  17. // It's better to use a char[] as shown here.
  18. // If you use a const char* or a String, ArduinoJson will
  19. // have to make a copy of the input in the JsonBuffer.
  20. uint8_t input[] = {131, 166, 115, 101, 110, 115, 111, 114, 163, 103, 112, 115,
  21. 164, 116, 105, 109, 101, 206, 80, 147, 50, 248, 164, 100,
  22. 97, 116, 97, 146, 203, 64, 72, 96, 199, 58, 188, 148,
  23. 112, 203, 64, 2, 106, 146, 230, 33, 49, 169};
  24. // This MessagePack document contains:
  25. // {
  26. // "sensor": "gps",
  27. // "time": 1351824120,
  28. // "data": [48.75608, 2.302038]
  29. // }
  30. // doc 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. DeserializationError error = deserializeMsgPack(doc, input);
  36. // Test if parsing succeeds.
  37. if (error) {
  38. std::cerr << "deserializeMsgPack() failed: " << error.c_str() << std::endl;
  39. return 1;
  40. }
  41. // Fetch values.
  42. //
  43. // Most of the time, you can rely on the implicit casts.
  44. // In other case, you can do doc["time"].as<long>();
  45. const char* sensor = doc["sensor"];
  46. long time = doc["time"];
  47. double latitude = doc["data"][0];
  48. double longitude = doc["data"][1];
  49. // Print values.
  50. std::cout << sensor << std::endl;
  51. std::cout << time << std::endl;
  52. std::cout << latitude << std::endl;
  53. std::cout << longitude << std::endl;
  54. return 0;
  55. }