get_to.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include <iostream>
  2. #include <unordered_map>
  3. #include <nlohmann/json.hpp>
  4. using json = nlohmann::json;
  5. int main()
  6. {
  7. // create a JSON value with different types
  8. json json_types =
  9. {
  10. {"boolean", true},
  11. {
  12. "number", {
  13. {"integer", 42},
  14. {"floating-point", 17.23}
  15. }
  16. },
  17. {"string", "Hello, world!"},
  18. {"array", {1, 2, 3, 4, 5}},
  19. {"null", nullptr}
  20. };
  21. bool v1;
  22. int v2;
  23. short v3;
  24. float v4;
  25. int v5;
  26. std::string v6;
  27. std::vector<short> v7;
  28. std::unordered_map<std::string, json> v8;
  29. // use explicit conversions
  30. json_types["boolean"].get_to(v1);
  31. json_types["number"]["integer"].get_to(v2);
  32. json_types["number"]["integer"].get_to(v3);
  33. json_types["number"]["floating-point"].get_to(v4);
  34. json_types["number"]["floating-point"].get_to(v5);
  35. json_types["string"].get_to(v6);
  36. json_types["array"].get_to(v7);
  37. json_types.get_to(v8);
  38. // print the conversion results
  39. std::cout << v1 << '\n';
  40. std::cout << v2 << ' ' << v3 << '\n';
  41. std::cout << v4 << ' ' << v5 << '\n';
  42. std::cout << v6 << '\n';
  43. for (auto i : v7)
  44. {
  45. std::cout << i << ' ';
  46. }
  47. std::cout << "\n\n";
  48. for (auto i : v8)
  49. {
  50. std::cout << i.first << ": " << i.second << '\n';
  51. }
  52. }