xref: /third_party/json/docs/examples/get_ref.cpp (revision c5f01b2f)
1#include <iostream>
2#include <nlohmann/json.hpp>
3
4using json = nlohmann::json;
5
6int main()
7{
8    // create a JSON number
9    json value = 17;
10
11    // explicitly getting references
12    auto r1 = value.get_ref<const json::number_integer_t&>();
13    auto r2 = value.get_ref<json::number_integer_t&>();
14
15    // print the values
16    std::cout << r1 << ' ' << r2 << '\n';
17
18    // incompatible type throws exception
19    try
20    {
21        auto r3 = value.get_ref<json::number_float_t&>();
22    }
23    catch (json::type_error& ex)
24    {
25        std::cout << ex.what() << '\n';
26    }
27}
28