Add rfl::DefaultIfMissing; fixes #163, #167, #185 (#189)

This commit is contained in:
Dr. Patrick Urbanke (劉自成)
2024-09-15 19:38:33 +02:00
committed by GitHub
parent dfc24ad932
commit 54c2a84650
12 changed files with 471 additions and 3 deletions
+2
View File
@@ -44,3 +44,5 @@ 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"}]}
```
**NOTE**: If you want to explicitly set default values for your fields and/or you want all fields to be optional, please consider using the `rfl::DefaultIfMissing` processor. You will find more information in the section on processors in this documentation.
+42 -1
View File
@@ -34,6 +34,7 @@ The resulting JSON string looks like this:
reflect-cpp currently supports the following processors:
- `rfl::AddStructName`
- `rfl::DefaultIfMissing`
- `rfl::NoFieldNames`
- `rfl::NoOptionals`
- `rfl::UnderlyingEnums`
@@ -42,7 +43,7 @@ reflect-cpp currently supports the following processors:
### `rfl::AddStructName`
It is also possible to add the struct name as an addtional field, like this:
It is also possible to add the struct name as an additional field, like this:
```cpp
const auto json_string =
@@ -58,6 +59,46 @@ The resulting JSON string looks like this:
{"type":"Person","first_name":"Homer","last_name":"Simpson","age":45}
```
### `rfl::DefaultIfMissing`
The `rfl::DefaultIfMissing` processor is only relevant for reading data. For writing data, it will make no difference.
Usually, when fields are missing in the input data, this will lead to an error
(unless they are optional fields).
But if you pass the `rfl::DefaultIfMissing` processor, then missing fields will be
replaced by their default value.
For instance, consider the following struct:
```cpp
struct Person {
std::string first_name;
std::string last_name = "Simpson";
std::string town;
};
```
Suppose you are reading a JSON like this:
```json
{"first_name":"Homer"}
```
```cpp
rfl::json::read<Person, rfl::DefaultIfMissing>(json_string);
```
Then the resulting struct will be equivalent to what you would
have gotten had you read the following JSON string:
```json
{"first_name":"Homer","last_name":"Simpson","town":""}
```
`last_name` and `town` have been replaced by the default values.
Because you have not passed a default value to town, the default value
of the type is used instead.
### `rfl::NoFieldNames`
We can also remove the field names altogether: