nlohmann_define_type_non_intrusive_with_default_explicit.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #include <iostream>
  2. #include <nlohmann/json.hpp>
  3. using json = nlohmann::json;
  4. using namespace nlohmann::literals;
  5. namespace ns
  6. {
  7. struct person
  8. {
  9. std::string name = "John Doe";
  10. std::string address = "123 Fake St";
  11. int age = -1;
  12. person() = default;
  13. person(std::string name_, std::string address_, int age_)
  14. : name(std::move(name_)), address(std::move(address_)), age(age_)
  15. {}
  16. };
  17. void to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)
  18. {
  19. nlohmann_json_j["name"] = nlohmann_json_t.name;
  20. nlohmann_json_j["address"] = nlohmann_json_t.address;
  21. nlohmann_json_j["age"] = nlohmann_json_t.age;
  22. }
  23. void from_json(const nlohmann::json& nlohmann_json_j, person& nlohmann_json_t)
  24. {
  25. person nlohmann_json_default_obj;
  26. nlohmann_json_t.name = nlohmann_json_j.value("name", nlohmann_json_default_obj.name);
  27. nlohmann_json_t.address = nlohmann_json_j.value("address", nlohmann_json_default_obj.address);
  28. nlohmann_json_t.age = nlohmann_json_j.value("age", nlohmann_json_default_obj.age);
  29. }
  30. } // namespace ns
  31. int main()
  32. {
  33. ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60};
  34. // serialization: person -> json
  35. json j = p;
  36. std::cout << "serialization: " << j << std::endl;
  37. // deserialization: json -> person
  38. json j2 = R"({"address": "742 Evergreen Terrace", "age": 40, "name": "Homer Simpson"})"_json;
  39. auto p2 = j2.get<ns::person>();
  40. // incomplete deserialization:
  41. json j3 = R"({"address": "742 Evergreen Terrace", "name": "Maggie Simpson"})"_json;
  42. auto p3 = j3.get<ns::person>();
  43. std::cout << "roundtrip: " << json(p3) << std::endl;
  44. }