1#include <iostream> 2#include <nlohmann/json.hpp> 3 4using json = nlohmann::json; 5 6namespace ns 7{ 8// a simple struct to model a person (not default constructible) 9struct person 10{ 11 person(std::string n, std::string a, int aa) 12 : name(std::move(n)), address(std::move(a)), age(aa) 13 {} 14 15 std::string name; 16 std::string address; 17 int age; 18}; 19} // namespace ns 20 21namespace nlohmann 22{ 23template <> 24struct adl_serializer<ns::person> 25{ 26 static ns::person from_json(const json& j) 27 { 28 return {j.at("name"), j.at("address"), j.at("age")}; 29 } 30 31 // Here's the catch! You must provide a to_json method! Otherwise, you 32 // will not be able to convert person to json, since you fully 33 // specialized adl_serializer on that type 34 static void to_json(json& j, ns::person p) 35 { 36 j["name"] = p.name; 37 j["address"] = p.address; 38 j["age"] = p.age; 39 } 40}; 41} // namespace nlohmann 42 43int main() 44{ 45 json j; 46 j["name"] = "Ned Flanders"; 47 j["address"] = "744 Evergreen Terrace"; 48 j["age"] = 60; 49 50 auto p = j.get<ns::person>(); 51 52 std::cout << p.name << " (" << p.age << ") lives in " << p.address << std::endl; 53} 54