to_ubjson.cpp 1.4 KB

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