forked from haenoe/json-questions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
64 lines (49 loc) · 1.51 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <map>
#include <string>
#include "include/nlohmann/json.hpp"
const nlohmann::json & valueAt(const nlohmann::json & map, const std::string & key)
{
return map[key];
}
const nlohmann::json::object_t & getObjectRef(const nlohmann::json & obj)
{
return obj.get_ref<const nlohmann::json::object_t &>();
}
const nlohmann::json::string_t & getStringRef(const nlohmann::json & obj)
{
return obj.get_ref<const nlohmann::json::string_t &>();
}
const nlohmann::json::object_t getObject(const nlohmann::json & obj)
{
return obj.get<const nlohmann::json::object_t>();
}
const nlohmann::json::string_t getString(const nlohmann::json & obj)
{
return obj.get<const nlohmann::json::string_t>();
}
int main()
{
nlohmann::json j2 = {
{"string", "foo"},
{"object", {
{"currency", "USD"},
{"value", 42.99}
}}
};
auto object = getObject(valueAt(j2, "object"));
std::cout << "object" << '\n';
std::cout << object << '\n';
auto nestedObject = getString(valueAt(object, "currency"));
std::cout << "nestedObject" << '\n';
// This works
std::cout << nestedObject << '\n';
// ------------------------------------------------------------------
auto & objectRef = getObjectRef(valueAt(j2, "object"));
std::cout << "objectRef" << '\n';
std::cout << objectRef << '\n';
auto & nestedObjectRef = getStringRef(valueAt(objectRef, "currency"));
std::cout << "nestedObjectRef" << '\n';
// Here `nestedObject` seems to be empty.
std::cout << nestedObjectRef << '\n';
}