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

Indexes created Thu Nov 07 10:32:03 CST 2024