2017-07-09 11:51:38 +02:00
|
|
|
#include <iostream>
|
2015-06-24 15:16:32 +02:00
|
|
|
#include <unordered_map>
|
2017-07-09 11:51:38 +02:00
|
|
|
#include "json.hpp"
|
2015-06-24 15:16:32 +02:00
|
|
|
|
2016-01-30 20:23:14 +01:00
|
|
|
using json = nlohmann::json;
|
2015-06-24 15:16:32 +02:00
|
|
|
|
|
|
|
int main()
|
|
|
|
{
|
|
|
|
// create a JSON value with different types
|
|
|
|
json json_types =
|
|
|
|
{
|
|
|
|
{"boolean", true},
|
|
|
|
{
|
|
|
|
"number", {
|
|
|
|
{"integer", 42},
|
|
|
|
{"floating-point", 17.23}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
{"string", "Hello, world!"},
|
|
|
|
{"array", {1, 2, 3, 4, 5}},
|
|
|
|
{"null", nullptr}
|
|
|
|
};
|
|
|
|
|
|
|
|
// use implicit conversions
|
|
|
|
bool v1 = json_types["boolean"];
|
|
|
|
int v2 = json_types["number"]["integer"];
|
|
|
|
short v3 = json_types["number"]["integer"];
|
|
|
|
float v4 = json_types["number"]["floating-point"];
|
|
|
|
int v5 = json_types["number"]["floating-point"];
|
|
|
|
std::string v6 = json_types["string"];
|
|
|
|
std::vector<short> v7 = json_types["array"];
|
|
|
|
std::unordered_map<std::string, json> v8 = json_types;
|
|
|
|
|
|
|
|
// print the conversion results
|
|
|
|
std::cout << v1 << '\n';
|
|
|
|
std::cout << v2 << ' ' << v3 << '\n';
|
|
|
|
std::cout << v4 << ' ' << v5 << '\n';
|
|
|
|
std::cout << v6 << '\n';
|
|
|
|
|
|
|
|
for (auto i : v7)
|
|
|
|
{
|
|
|
|
std::cout << i << ' ';
|
|
|
|
}
|
|
|
|
std::cout << "\n\n";
|
|
|
|
|
|
|
|
for (auto i : v8)
|
|
|
|
{
|
|
|
|
std::cout << i.first << ": " << i.second << '\n';
|
|
|
|
}
|
2017-03-08 23:12:13 +01:00
|
|
|
|
|
|
|
// example for an exception
|
|
|
|
try
|
|
|
|
{
|
|
|
|
bool v1 = json_types["string"];
|
|
|
|
}
|
|
|
|
catch (json::type_error& e)
|
|
|
|
{
|
|
|
|
std::cout << e.what() << '\n';
|
|
|
|
}
|
2015-06-24 15:16:32 +02:00
|
|
|
}
|