xref: /third_party/json/docs/examples/object.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 JSON objects
9c5f01b2fSopenharmony_ci    json j_no_init_list = json::object();
10c5f01b2fSopenharmony_ci    json j_empty_init_list = json::object({});
11c5f01b2fSopenharmony_ci    json j_list_of_pairs = json::object({ {"one", 1}, {"two", 2} });
12c5f01b2fSopenharmony_ci
13c5f01b2fSopenharmony_ci    // serialize the JSON objects
14c5f01b2fSopenharmony_ci    std::cout << j_no_init_list << '\n';
15c5f01b2fSopenharmony_ci    std::cout << j_empty_init_list << '\n';
16c5f01b2fSopenharmony_ci    std::cout << j_list_of_pairs << '\n';
17c5f01b2fSopenharmony_ci
18c5f01b2fSopenharmony_ci    // example for an exception
19c5f01b2fSopenharmony_ci    try
20c5f01b2fSopenharmony_ci    {
21c5f01b2fSopenharmony_ci        // can only create an object from a list of pairs
22c5f01b2fSopenharmony_ci        json j_invalid_object = json::object({{ "one", 1, 2 }});
23c5f01b2fSopenharmony_ci    }
24c5f01b2fSopenharmony_ci    catch (json::type_error& e)
25c5f01b2fSopenharmony_ci    {
26c5f01b2fSopenharmony_ci        std::cout << e.what() << '\n';
27c5f01b2fSopenharmony_ci    }
28c5f01b2fSopenharmony_ci}
29

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