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