to_bjdata.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <nlohmann/json.hpp>
  4. using json = nlohmann::json;
  5. using namespace nlohmann::literals;
  6. // function to print BJData's diagnostic format
  7. void print_byte(uint8_t byte)
  8. {
  9. if (32 < byte and byte < 128)
  10. {
  11. std::cout << (char)byte;
  12. }
  13. else
  14. {
  15. std::cout << (int)byte;
  16. }
  17. }
  18. int main()
  19. {
  20. // create a JSON value
  21. json j = R"({"compact": true, "schema": false})"_json;
  22. // serialize it to BJData
  23. std::vector<std::uint8_t> v = json::to_bjdata(j);
  24. // print the vector content
  25. for (auto& byte : v)
  26. {
  27. print_byte(byte);
  28. }
  29. std::cout << std::endl;
  30. // create an array of numbers
  31. json array = {1, 2, 3, 4, 5, 6, 7, 8};
  32. // serialize it to BJData using default representation
  33. std::vector<std::uint8_t> v_array = json::to_bjdata(array);
  34. // serialize it to BJData using size optimization
  35. std::vector<std::uint8_t> v_array_size = json::to_bjdata(array, true);
  36. // serialize it to BJData using type optimization
  37. std::vector<std::uint8_t> v_array_size_and_type = json::to_bjdata(array, true, true);
  38. // print the vector contents
  39. for (auto& byte : v_array)
  40. {
  41. print_byte(byte);
  42. }
  43. std::cout << std::endl;
  44. for (auto& byte : v_array_size)
  45. {
  46. print_byte(byte);
  47. }
  48. std::cout << std::endl;
  49. for (auto& byte : v_array_size_and_type)
  50. {
  51. print_byte(byte);
  52. }
  53. std::cout << std::endl;
  54. }