diff --git a/docs/optional_fields.md b/docs/optional_fields.md new file mode 100644 index 00000000..23440fd8 --- /dev/null +++ b/docs/optional_fields.md @@ -0,0 +1,46 @@ +# Optional fields + +Usually, when you set up a struct, all of the fields are required. For instance, in the previous example, +we generated a JSON string like this: + +```json +{"firstName":"Bart","lastName":"Simpson","children":[]} +``` + +Likewise, if we read the JSON string and the field "children" is missing, that will result in a runtime error. + +But Bart doesn't have any children. After all, he's only 10 years old. To indicate to the library that the field children is optional, +we can use either `std::optional`, `std::shared_ptr` or `std::unique_ptr` (TODO: unique_ptr currently unsupported). + +If `std::optional` is `std::nullopt` or any of the smart pointers is a `nullptr`, +then the field will not be written to the JSON string. Likewise, it is not required +when you read the JSON string, the fields will not be required. + +So this is how we could rewrite the previous example: + +```cpp +struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name = "Simpson"; + + // Indicates to the library that the field is optional. + rfl::Field<"children", std::optional>> children = rfl::default_value; +}; + +const auto bart = Person{.first_name = "Bart"}; + +const auto lisa = Person{.first_name = "Lisa"}; + +const auto maggie = Person{.first_name = "Maggie"}; + +const auto homer = Person{.first_name = "Homer", + .children = std::vector({bart, lisa, maggie})}; + +const auto json_string = rfl::json::write(homer); +``` + +Now, the field "children" is missing for Bart, Lisa and Maggie: + +```json +{"firstName":"Homer","lastName":"Simpson","children":[{"firstName":"Bart","lastName":"Simpson"},{"firstName":"Lisa","lastName":"Simpson"},{"firstName":"Maggie","lastName":"Simpson"}]} +```