From 4fca517f8f37b9028f12602bb067f0e562935e74 Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Wed, 25 Oct 2023 20:31:40 +0200 Subject: [PATCH] Added documentation on custom constructors --- docs/json.md | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/docs/json.md b/docs/json.md index db5c91e1..cc24e5f0 100644 --- a/docs/json.md +++ b/docs/json.md @@ -2,6 +2,8 @@ For JSON support, you must also include the header ``. +## Reading and writing + Suppose you have a struct like this: ```cpp @@ -26,6 +28,8 @@ const auto person = Person{...}; const std::string json_string = rfl::json::write(person); ``` +## Loading and saving + You can also load and save to disc using a very similar syntax: ```cpp @@ -35,5 +39,43 @@ const auto person = Person{...}; rfl::json::save("/path/to/file.json", person); ``` +## Custom constructors +One of the great things about C++ is that it gives you control over +when and how you code is compiled. + +For large and complex systems of structs, it is often a good idea to split up +your code into smaller compilation units. You can do so using custom constructors. + +For the JSON format, these must be a static function on your struct or class called +`from_json_obj` that take a `rfl::json::Reader::InputVarType` as input and return +the class or the class wrapped in `rfl::Result`. + +In your header file you can write something like this: + +```cpp +struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name; + rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday; + + using JSONVar = typename rfl::json::Reader::InputVarType; + static rfl::Result from_json_obj(const JSONVar& _obj); +}; +``` + +And in your source file, you implement `from_json_obj` as follows: + +```cpp +rfl::Result Person::from_json_obj(const JSONVar& _obj) { + const auto from_nt = [](auto&& _nt) { + return rfl::from_named_tuple(std::move(_nt)); + }; + return rfl::json::read>(_obj) + .transform(from_nt); +} +``` + +This will force the compiler to only compile the JSON parsing when the +source file is compiled.