pre::json Namespace Reference

Functions

template<class T >
nlohmann::json to_json (const T &value)
 Serialize to a JSON object any C++ object of any type, even your own types. More...
 
template<class T >
from_json (const std::string &serialized_json)
 Deserialize any json object or value in a C++ type. More...
 
template<class T >
from_json (const nlohmann::json &json_object)
 Same as pre::json::from_json(const std::string&) but directly with a JSON.
 

Detailed Description

Serialize and Deserialize any C++ type, class... into JSON

Function Documentation

template<class T >
T pre::json::from_json ( const std::string &  serialized_json)

Deserialize any json object or value in a C++ type.

Parameters
TThe result type wanted from the deserialization. that will be filled from the given json_object.
serialized_jsonjson to deserialize

Deserialize any json object or value in a C++ type.

The function throws an std::exception if a mandatory member isn't found, but doesn't in the case of boost::optional.

The type has to be supported, or adapted with BOOST_FUSION_ADAPT_STRUCT.

See below for supported types.

Example

#include <iostream>
#include <pre/json/from_json.hpp>
struct customer {
std::string name;
size_t money_spent;
std::vector<std::string> interests;
};
BOOST_FUSION_ADAPT_STRUCT(customer,
name,
money_spent,
interests)
...
std::string string_to_deserialize =
"{\"interests\":[\"sport articles\"], \"money_spent\":50, \"name\":\"Mrs. Fraulein\"}";
customer my_customer = pre::json::from_json<customer>(string_to_deserialize);
std::cout << "Customer " << my_customer.name << " spent " <<
my_customer.money_spent << std::endl;

Supported types

Returns
the type wanted if it succeed find all member and value in the json.
template<class T >
nlohmann::json pre::json::to_json ( const T &  value)

Serialize to a JSON object any C++ object of any type, even your own types.

Parameters
TAny of the Supported Types.
valueA value adapted with BOOST_FUSION_ADAPT_STRUCT. This value can be any aggregate with nested aggregate or any C++ types.

Serialize to a JSON object any C++ object of any type, even your own types.

It uses type traits introspection as well as Boost.Fusion reflection information to generate JSON from any types.

Example

#include <iostream>
#include <pre/json/to_json.hpp>
struct customer {
std::string name;
size_t money_spent;
std::vector<std::string> interests;
};
BOOST_FUSION_ADAPT_STRUCT(customer,
name,
money_spent,
interests)
...
customer my_customer{
"Mr. Dupond",
1000,
{"sport articles", "food", "tools"}
};
std::cout << pre::json::to_json(my_customer) << std::endl;

Supported types

Returns
An nlohmann::json object directly streamable to std::cout or convertible to string.