Merge branch 'main' of github.com:getml/reflect-cpp

This commit is contained in:
Patrick Urbanke
2023-10-07 12:24:00 +02:00
3 changed files with 50 additions and 2 deletions
+2 -2
View File
@@ -30,7 +30,7 @@ Design principles for reflect-cpp include:
#include <rfl/json.hpp>
#include <rfl.hpp>
// "firstName", "lastName" and "children" are the field names
// "firstName", "lastName", "birthday" and "children" are the field names
// as they will appear in the JSON. The C++ standard is
// snake case, the JSON standard is camel case, so the names
// will not always be identical.
@@ -78,7 +78,7 @@ This results in the following JSON string:
We can also create structs from the string:
```
```cpp
auto homer2 = rfl::json::read<Person>(json_string).value();
// Fields can be accessed like this:
+3
View File
@@ -16,6 +16,9 @@
1.6) [rfl::Ref](https://github.com/getml/reflect-cpp/blob/main/docs/rfl_ref.md) - For defining recursive structures.
1.7) [rfl::Timestamp](https://github.com/getml/reflect-cpp/blob/main/docs/timestamps.md) - For serializing and deserializing timestamps.
## 2) Custom classes
2.1) [Custom classes](https://github.com/getml/reflect-cpp/blob/main/docs/custom_classes.md) - For custom classes with private fields.
+45
View File
@@ -0,0 +1,45 @@
# `rfl::Timestamp`
`rfl::Timestamp` is a simple wrapper around `std::tm` (https://en.cppreference.com/w/cpp/chrono/c/tm).
As its template parameter it includes the time stamp format for serialization and deserialization.
Here is a reference for for how you can specify the format:
https://en.cppreference.com/w/cpp/chrono/c/strftime
In fact, `rfl::Timestamp` calls `strftime` and `strptime` under-the-hood.
They can be used in your struct like this:
```cpp
struct Person {
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday;
};
```
An `rfl::Timestamp` can be constructed from either a string or a `std::tm` struct.
```cpp
const auto person1 = Person{.birthday = "1970-01-01"};
const auto person2 = Person{.birthday = std::tm{...}};
```
You can access the underlying `std::tm` struct using the `.tm()` method and you can generate
the string representation using the `.str()` method.
```cpp
const std::tm birthday = person1.birthday().tm();
std::cout << person1.birthday().str() << std::endl;
```
Note that constructing `rfl::Timestamp` from a string is convenient, but it might result in
an exception.
To avoid the exception you can also use `Timestamp<...>::from_string(...)`, which will
return an `rfl::Result<Timestamp<...>>` or `rfl::Error`.
```cpp
const rfl::Result<rfl::Timestamp<"%Y-%m-%d">> result = rfl::Timestamp<"%Y-%m-%d">::from_string("1970-01-01");
const rfl::Result<rfl::Timestamp<"%Y-%m-%d">> error = rfl::Timestamp<"%Y-%m-%d">::from_string("not a proper time format");
```