| 1 |
### Convenience Macros |
| 2 |
|
| 3 |
The `jsoncons` library provides a number of macros that can be used to generate the code to specialize `json_type_traits` |
| 4 |
for a user-defined class. |
| 5 |
|
| 6 |
Macro names follow naming conventions. |
| 7 |
|
| 8 |
Component | Description |
| 9 |
----------|-------------------- |
| 10 |
TPL | Template class with a specified number of template parameters |
| 11 |
ALL | All data members are mandatory |
| 12 |
N | A specified number of data members are mandatory |
| 13 |
MEMBER | Accesses and modifies class data members |
| 14 |
CTOR | Requires constructor that takes all data members in the order they appear in the list |
| 15 |
GETTER | Accesses data members through getter functions |
| 16 |
SETTER | Modifies data members through setter functions |
| 17 |
NAME | Serialize with provided names (instead of C++ member names) |
| 18 |
|
| 19 |
The `_NAME_` macros are the most general. They allow optional |
| 20 |
parameters that affect data member mappings. Optionality is |
| 21 |
indicated by square brackets. |
| 22 |
|
| 23 |
The maximum number of parameters allowed in macros is 70 (since 0.168.4). |
| 24 |
Previously it was 50. |
| 25 |
|
| 26 |
```cpp |
| 27 |
#include <jsoncons/json_type_traits.hpp> |
| 28 |
|
| 29 |
JSONCONS_N_MEMBER_TRAITS(class_name,num_mandatory, |
| 30 |
member0,member1,...) (1) |
| 31 |
|
| 32 |
JSONCONS_ALL_MEMBER_TRAITS(class_name, |
| 33 |
member0,member1,...) (2) |
| 34 |
|
| 35 |
JSONCONS_TPL_N_MEMBER_TRAITS(num_template_params, |
| 36 |
class_name,num_mandatory, |
| 37 |
member0,member1,...) (3) |
| 38 |
|
| 39 |
JSONCONS_TPL_ALL_MEMBER_TRAITS(num_template_params, |
| 40 |
class_name, |
| 41 |
member0,member1,...) (4) |
| 42 |
|
| 43 |
JSONCONS_N_MEMBER_NAME_TRAITS(class_name,num_mandatory, |
| 44 |
(member0,serialized_name0[,mode0,match0,into0,from0]), |
| 45 |
(member1,serialized_name1[,mode1,match1,into1,from1])...) (5) |
| 46 |
|
| 47 |
JSONCONS_ALL_MEMBER_NAME_TRAITS(class_name, |
| 48 |
(member0,serialized_name0[,mode0,match0,into0,from0]), |
| 49 |
(member1,serialized_name1[,mode1,match1,into1,from1])...) (6) |
| 50 |
|
| 51 |
JSONCONS_TPL_N_MEMBER_NAME_TRAITS(num_template_params, |
| 52 |
class_name,num_mandatory, |
| 53 |
(member0,serialized_name0[,mode0,match0,into0,from0]), |
| 54 |
(member1,serialized_name1[,mode1,match1,into1,from1])...) (7) |
| 55 |
|
| 56 |
JSONCONS_TPL_ALL_MEMBER_NAME_TRAITS(num_template_params, |
| 57 |
class_name, |
| 58 |
(member0,serialized_name0[,mode0,match0,into0,from0]), |
| 59 |
(member1,serialized_name1[,mode1,match1,into1,from1])...) (8) |
| 60 |
|
| 61 |
JSONCONS_ENUM_TRAITS(enum_name,enumerator0,enumerator1,...) (9) |
| 62 |
|
| 63 |
JSONCONS_ENUM_NAME_TRAITS(enum_name, |
| 64 |
(enumerator0,serialized_name0), |
| 65 |
(enumerator1,serialized_name1)...) (10) |
| 66 |
|
| 67 |
JSONCONS_N_CTOR_GETTER_TRAITS(class_name,num_mandatory, |
| 68 |
getter0, |
| 69 |
getter1,...) (11) |
| 70 |
|
| 71 |
JSONCONS_ALL_CTOR_GETTER_TRAITS(class_name, |
| 72 |
getter0,getter1,...) (12) |
| 73 |
|
| 74 |
JSONCONS_TPL_N_CTOR_GETTER_TRAITS(num_template_params, |
| 75 |
class_name,num_mandatory, |
| 76 |
getter0,getter1,...) (13) |
| 77 |
|
| 78 |
JSONCONS_TPL_ALL_CTOR_GETTER_TRAITS(num_template_params, |
| 79 |
class_name, |
| 80 |
getter0,getter1,...) (14) |
| 81 |
|
| 82 |
JSONCONS_N_CTOR_GETTER_NAME_TRAITS(class_name,num_mandatory, |
| 83 |
(getter0,serialized_name0[,mode0,match0,into0,from0]), |
| 84 |
(getter1,serialized_name1[,mode1,match1,into1,from1])...) (15) |
| 85 |
|
| 86 |
JSONCONS_ALL_CTOR_GETTER_NAME_TRAITS(class_name, |
| 87 |
(getter0,serialized_name0[,mode0,match0,into0,from0]), |
| 88 |
(getter1,serialized_name1[,mode1,match1,into1,from1])...) (16) |
| 89 |
|
| 90 |
JSONCONS_TPL_N_CTOR_GETTER_NAME_TRAITS(num_template_params, |
| 91 |
class_name,num_mandatory, |
| 92 |
(getter0,serialized_name0[,mode0,match0,into0,from0]), |
| 93 |
(getter1,serialized_name1[,mode1,match1,into1,from1])...) (17) |
| 94 |
|
| 95 |
JSONCONS_TPL_ALL_CTOR_GETTER_NAME_TRAITS(num_template_params, |
| 96 |
class_name, |
| 97 |
(getter0,serialized_name0[,mode0,match0,into0,from0]), |
| 98 |
(getter1,serialized_name1[,mode1,match1,into1,from1])...) (18) |
| 99 |
|
| 100 |
JSONCONS_N_GETTER_SETTER_TRAITS(class_name,get_prefix,set_prefix,num_mandatory, |
| 101 |
property0,property1,...) (19) |
| 102 |
|
| 103 |
JSONCONS_ALL_GETTER_SETTER_TRAITS(class_name,get_prefix,set_prefix, |
| 104 |
property0,property1,...) (20) |
| 105 |
|
| 106 |
JSONCONS_TPL_N_GETTER_SETTER_TRAITS(num_template_params, |
| 107 |
class_name,get_prefix,set_prefix,num_mandatory, |
| 108 |
property0,property1,...) (21) |
| 109 |
|
| 110 |
JSONCONS_TPL_ALL_GETTER_SETTER_TRAITS(num_template_params, |
| 111 |
class_name,get_prefix,set_prefix, |
| 112 |
property0,property1,...) (22) |
| 113 |
|
| 114 |
JSONCONS_N_GETTER_SETTER_NAME_TRAITS(class_name,num_mandatory, |
| 115 |
(getter0,setter0,serialized_name0[,mode0,match0,into0,from0]), |
| 116 |
(getter1,setter1,serialized_name1[,mode1,match1,into1,from1])...) (23) |
| 117 |
|
| 118 |
JSONCONS_ALL_GETTER_SETTER_NAME_TRAITS(class_name, |
| 119 |
(getter0,setter0,serialized_name0[,mode0,match0,into0,from0]), |
| 120 |
(getter1,setter1,serialized_name1[,mode1,match1,into1,from1])...) (24) |
| 121 |
|
| 122 |
JSONCONS_TPL_N_GETTER_SETTER_NAME_TRAITS(num_template_params, |
| 123 |
class_name,num_mandatory, |
| 124 |
(getter0,setter0,serialized_name0[,mode0,match0,into0,from0]), |
| 125 |
(getter1,setter1,serialized_name1[,mode1,match1,into1,from1])...) (25) |
| 126 |
|
| 127 |
JSONCONS_TPL_ALL_GETTER_SETTER_NAME_TRAITS(num_template_params, |
| 128 |
class_name, |
| 129 |
(getter0,setter0,serialized_name0[,mode0,match0,into0,from0]), |
| 130 |
(getter1,setter1,serialized_name1[,mode1,match1,into1,from1])...) (26) |
| 131 |
|
| 132 |
JSONCONS_POLYMORPHIC_TRAITS(base_class_name,derived_class_name0,derived_class_name1,...) (27) |
| 133 |
``` |
| 134 |
|
| 135 |
(1)-(4) generate the code to specialize `json_type_traits` for a class from member data. |
| 136 |
The serialized names are the stringified member names. |
| 137 |
When decoding to a C++ data structure, |
| 138 |
(1) and (3) require that the first `num_mandatory` member names be present in the JSON, |
| 139 |
the rest can have default values. (2) and (4) |
| 140 |
require that all member names be present in the JSON. The class must have a default constructor. |
| 141 |
If the member data or default constructor are private, the macro `JSONCONS_TYPE_TRAITS_FRIEND` |
| 142 |
will make them accessible to `json_type_traits`, used so |
| 143 |
|
| 144 |
```cpp |
| 145 |
class MyClass |
| 146 |
{ |
| 147 |
JSONCONS_TYPE_TRAITS_FRIEND |
| 148 |
... |
| 149 |
}; |
| 150 |
``` |
| 151 |
|
| 152 |
(3)-(4) generate the code to specialize `json_type_traits` for a class template from member data. |
| 153 |
|
| 154 |
(5)-(8) generate the code to specialize `json_type_traits` for a class from member data. |
| 155 |
The serialized names are the provided names. The sequence of `(memberN,serialized_nameN)` |
| 156 |
pairs declares the member name and provided name for each of the class members |
| 157 |
that are part of the sequence. |
| 158 |
When decoding to a C++ data structure, |
| 159 |
(5) and (7) require that the first `num_mandatory` member names be present in the JSON, |
| 160 |
the rest can have default values. (6) and (8) |
| 161 |
require that all member names be present in the JSON. The class must have a default constructor. |
| 162 |
If the member data or default constructor are private, the macro `JSONCONS_TYPE_TRAITS_FRIEND` |
| 163 |
will make them accessible to `json_type_traits`. |
| 164 |
(7)-(8) generate the code to specialize `json_type_traits` for a class template from member data. |
| 165 |
|
| 166 |
(9) generates the code to specialize `json_type_traits` for an enumerated type from its enumerators. |
| 167 |
The serialized name is the stringified enumerator name. |
| 168 |
|
| 169 |
(10) generates the code to specialize `json_type_traits` for an enumerated type from its enumerators. |
| 170 |
The serialized name is the provided name. The sequence of `(enumeratorN,serialized_nameN)` |
| 171 |
pairs declares the named constant and provided name for each of the enumerators |
| 172 |
that are part of the sequence. |
| 173 |
|
| 174 |
(11)-(14) generate the code to specialize `json_type_traits` for a class from a constructor and get functions. |
| 175 |
The serialized names are the stringified field names. |
| 176 |
When decoding to a C++ data structure, |
| 177 |
(11) and (13) require that the first `num_mandatory` member names be present in the JSON, |
| 178 |
the rest can have default values. (12) and (14) |
| 179 |
require that all member names be present in the JSON. The class must have a constructor such that the return types |
| 180 |
of the get functions are convertible to its parameters, taken in order. |
| 181 |
(13)-(14) generate the code to specialize `json_type_traits` for a class template from a constructor and get functions. |
| 182 |
|
| 183 |
(15)-(18) generate the code to specialize `json_type_traits` for a class from a constructor and get functions. |
| 184 |
The serialized names are the provided names. The sequence of `(getterN,serialized_nameN)` |
| 185 |
pairs declares the get function and provided name for each of the class members |
| 186 |
that are part of the sequence. |
| 187 |
When decoding to a C++ data structure, |
| 188 |
(15) and (17) require that the first `num_mandatory` member names be present in the JSON, |
| 189 |
the rest can have default values. (16) and (18) |
| 190 |
require that all member names be present in the JSON. The class must have a constructor such that the return types |
| 191 |
of the get functions are convertible to its parameters, taken in order. |
| 192 |
(17)-(18) generate the code to specialize `json_type_traits` for a class template from a constructor and get functions. |
| 193 |
|
| 194 |
(19)-(22) generate the code to specialize `json_type_traits` for a class from get and set functions. |
| 195 |
The serialized names are the stringified field names. The get and set function names are |
| 196 |
formed from the concatenation of `get_prefix` and `set_prefix` with field name. |
| 197 |
(19) and (21) require that the first `num_mandatory` member names be present in the JSON, |
| 198 |
the rest can have default values. (20) and (22) |
| 199 |
require that all member names be present in the JSON. (21)-(22) generate the code to specialize `json_type_traits` |
| 200 |
for a class template from get and set functions. |
| 201 |
|
| 202 |
(23)-(26) generate the code to specialize `json_type_traits` for a class from get and set functions. |
| 203 |
The serialized names are the provided names. The sequence of `(getterN,setterN,serialized_nameN)` |
| 204 |
triples declares the get and set functions and provided name for each of the class members |
| 205 |
that are part of the sequence. When decoding to a C++ data structure, |
| 206 |
(23) and (25) require that the first `num_mandatory` member names be present in the JSON, |
| 207 |
the rest can have default values. (24) and (26) |
| 208 |
require that all member names be present in the JSON. The class must have a default constructor. |
| 209 |
(25)-(26) generate the code to specialize `json_type_traits` for a class template from get and set functions. |
| 210 |
|
| 211 |
(27) generates the code to specialize `json_type_traits` for `std::shared_ptr<base_class>` and `std::unique_ptr<base_class>`. |
| 212 |
Each derived class must have a `json_type_traits<Json,derived_class_name>` specialization. |
| 213 |
The type selection strategy is based on `json_type_traits<Json,derived_class_name>::is(const Json& j)`. |
| 214 |
In the case that `json_type_traits<Json,derived_class_name>` has been generated by one of the |
| 215 |
conveniences macros (1)-(26), the type selection strategy is based on the presence of members |
| 216 |
in the derived classes. |
| 217 |
|
| 218 |
#### Parameters |
| 219 |
|
| 220 |
<table border="0"> |
| 221 |
<tr> |
| 222 |
<td><code>class_name</code></td> |
| 223 |
<td>The name of a class or struct.</td> |
| 224 |
</tr> |
| 225 |
<tr> |
| 226 |
<td><code>enum_name</code></td> |
| 227 |
<td>The name of an enum type or enum class type.</td> |
| 228 |
</tr> |
| 229 |
<tr> |
| 230 |
<td><code>num_mandatory</code></td> |
| 231 |
<td>The number of mandatory class data members or accessors.</td> |
| 232 |
</tr> |
| 233 |
<tr> |
| 234 |
<td><code>num_template_params</code></td> |
| 235 |
<td>For a class template, the number of template parameters.</td> |
| 236 |
</tr> |
| 237 |
<tr> |
| 238 |
<td><code>memberN</code></td> |
| 239 |
<td>The name of a class data member. Class data members are normally modifiable, but may be <code>const</code> or <code>static const</code>. |
| 240 |
Data members that are <code>const</code> or <code>static const</code> are one-way serialized.</td> |
| 241 |
</tr> |
| 242 |
<tr> |
| 243 |
<td><code>propertyN</code></td> |
| 244 |
<td>The base name of a class getter or setter, with any get or set prefix stripped out.</td> |
| 245 |
</tr> |
| 246 |
<tr> |
| 247 |
<td><code>getterN</code></td> |
| 248 |
<td>The getter for a class data member.</td> |
| 249 |
</tr> |
| 250 |
<tr> |
| 251 |
<td><code>setterN</code></td> |
| 252 |
<td>The setter for a class data member.</td> |
| 253 |
</tr> |
| 254 |
<tr> |
| 255 |
<td><code>enumeratorN</code></td> |
| 256 |
<td>An enumerator.</td> |
| 257 |
</tr> |
| 258 |
<tr> |
| 259 |
<td><code>serialized_nameN</code></td> |
| 260 |
<td>Serialized name.</td> |
| 261 |
</tr> |
| 262 |
<tr> |
| 263 |
<td><code>modeN</code></td> |
| 264 |
<td>Indicates whether a data member is read-write (<code>JSONCONS_RDWR</code>) or read-only (<code>JSONCONS_RDONLY</code>). |
| 265 |
Read-only data members are serialized but not de-serialized. (since 0.157.0)</td> |
| 266 |
</tr> |
| 267 |
<tr> |
| 268 |
<td><code>matchN</code></td> |
| 269 |
<td>A function object that checks if a type that has <code>json_type_traits</code> specialization |
| 270 |
can be converted into a user value. |
| 271 |
It must have function call signature equivalent to |
| 272 |
<br/><br/><code> |
| 273 |
bool fun(const Type& a); |
| 274 |
</code><br/><br/> |
| 275 |
where <code>Type</code> matches the return type of function object <code>intoN</code>, if provided, |
| 276 |
and if not, the type of <code>memberN</code> (<code>_MEMBER_</code> traits) |
| 277 |
or the return type of an accessor (<code>_GETTER_ traits</code>). |
| 278 |
It returns <code>true</code> if the argument provided matches an allowed value, |
| 279 |
<code>false</code> otherwise. (since 0.157.0)</td> |
| 280 |
</tr> |
| 281 |
<tr> |
| 282 |
<td><code>intoN</code></td> |
| 283 |
<td>A function object that converts a user value into a type that has <code>json_type_traits</code> specialization. |
| 284 |
It must have function call signature equivalent to |
| 285 |
<br/><br/><code> |
| 286 |
Ret fun(const Type& a); |
| 287 |
</code><br/><br/> |
| 288 |
where <code>Type</code> matches the type of <code>memberN</code> (<code>_MEMBER_</code> traits) or the return type of an accessor (<code>_GETTER_ traits</code>), and <code>Ret</code> is the parameter type of function object <code>fromN</code> (if provided) |
| 289 |
or <code>Type</code> (if not). |
| 290 |
It can be a free function, a struct object with <code>operator()</code> defined, or a variable containing a lambda expression, |
| 291 |
but because it is used in an unevaluated context, it cannot be a lambda expression (at least until C++20). |
| 292 |
(since 0.157.0)</td> |
| 293 |
</tr> |
| 294 |
<tr> |
| 295 |
<td><code>fromN</code></td> |
| 296 |
<td>A function object that gets a user value from a type that has <code>json_type_traits</code> specialization. |
| 297 |
It must have function call signature equivalent to |
| 298 |
<br/><br/><code> |
| 299 |
Ret fun(const Type& a); |
| 300 |
</code><br/><br/> |
| 301 |
where <code>Type</code> is the return type of the function object <code>intoN</code>, |
| 302 |
and <code>Ret</code> is the is the type of <code>memberN</code> (<code>_MEMBER_</code> traits) or the return type of an accessor (<code>_GETTER_ traits</code>). |
| 303 |
Only used if <code>modeN</code> is <code>JSONCONS_RDWR</code>. (since 0.157.0)</td> |
| 304 |
</tr> |
| 305 |
<tr> |
| 306 |
<td><code>base_class_name</code></td> |
| 307 |
<td>The name of a base class.</td> |
| 308 |
</tr> |
| 309 |
<tr> |
| 310 |
<td><code>derived_class_nameN</code></td> |
| 311 |
<td>A class that is derived from the base class, and that has a <code>json_type_traits<Json,derived_class_nameN></code> specialization.</td> |
| 312 |
</tr> |
| 313 |
</table> |
| 314 |
|
| 315 |
These macro declarations must be placed at global scope, outside any namespace blocks, and `class_name`, |
| 316 |
`base_class_name` and `derived_class_nameN` must be a fully namespace qualified names. |
| 317 |
|
| 318 |
All of the `json_type_traits` specializations for type `T` generated by the convenience macros include a specialization of |
| 319 |
`is_json_type_traits_declared<T>` with member constant `value` equal **true**. |
| 320 |
|
| 321 |
### Examples |
| 322 |
|
| 323 |
[Specialize json_type_traits to support a book class](#A1) |
| 324 |
[Using JSONCONS_ALL_CTOR_GETTER_TRAITS to generate the json_type_traits](#A2) |
| 325 |
[Example with std::shared_ptr, std::unique_ptr and std::optional](#A3) |
| 326 |
[Serialize a polymorphic type based on the presence of members](#A4) |
| 327 |
[Ensuring type selection is possible](#A5) |
| 328 |
[Decode to a polymorphic type based on a type marker (since 0.157.0)](#A6) |
| 329 |
[An example with std::variant](#A7) |
| 330 |
[Type selection and std::variant](#A8) |
| 331 |
[Decode to a std::variant based on a type marker (since 0.158.0)](#A9) |
| 332 |
[Transform data member (since 0.157.0)](#A10) |
| 333 |
[Tidy data member (since 0.158.0)](#A11) |
| 334 |
|
| 335 |
<div id="A1"/> |
| 336 |
|
| 337 |
#### Specialize json_type_traits to support a book class. |
| 338 |
|
| 339 |
```cpp |
| 340 |
#include <iostream> |
| 341 |
#include <jsoncons/json.hpp> |
| 342 |
#include <vector> |
| 343 |
#include <string> |
| 344 |
|
| 345 |
namespace ns { |
| 346 |
struct book |
| 347 |
{ |
| 348 |
std::string author; |
| 349 |
std::string title; |
| 350 |
double price{0}; |
| 351 |
}; |
| 352 |
} // namespace ns |
| 353 |
|
| 354 |
JSONCONS_ALL_MEMBER_TRAITS(ns::book, author, title, price) |
| 355 |
|
| 356 |
using namespace jsoncons; // for convenience |
| 357 |
|
| 358 |
int main() |
| 359 |
{ |
| 360 |
const std::string s = R"( |
| 361 |
[ |
| 362 |
{ |
| 363 |
"author" : "Haruki Murakami", |
| 364 |
"title" : "Kafka on the Shore", |
| 365 |
"price" : 25.17 |
| 366 |
}, |
| 367 |
{ |
| 368 |
"author" : "Charles Bukowski", |
| 369 |
"title" : "Pulp", |
| 370 |
"price" : 22.48 |
| 371 |
} |
| 372 |
] |
| 373 |
)"; |
| 374 |
|
| 375 |
std::vector<ns::book> book_list = decode_json<std::vector<ns::book>>(s); |
| 376 |
|
| 377 |
std::cout << "(1)\n"; |
| 378 |
for (const auto& item : book_list) |
| 379 |
{ |
| 380 |
std::cout << item.author << ", " |
| 381 |
<< item.title << ", " |
| 382 |
<< item.price << "\n"; |
| 383 |
} |
| 384 |
|
| 385 |
std::cout << "\n(2)\n"; |
| 386 |
encode_json_pretty(book_list, std::cout); |
| 387 |
std::cout << "\n\n"; |
| 388 |
} |
| 389 |
``` |
| 390 |
Output: |
| 391 |
``` |
| 392 |
(1) |
| 393 |
Haruki Murakami, Kafka on the Shore, 25.17 |
| 394 |
Charles Bukowski, Pulp, 22.48 |
| 395 |
|
| 396 |
(2) |
| 397 |
[ |
| 398 |
{ |
| 399 |
"author": "Haruki Murakami", |
| 400 |
"price": 25.17, |
| 401 |
"title": "Kafka on the Shore" |
| 402 |
}, |
| 403 |
{ |
| 404 |
"author": "Charles Bukowski", |
| 405 |
"price": 22.48, |
| 406 |
"title": "Pulp" |
| 407 |
} |
| 408 |
] |
| 409 |
``` |
| 410 |
|
| 411 |
<div id="A2"/> |
| 412 |
|
| 413 |
#### Using JSONCONS_ALL_CTOR_GETTER_TRAITS to generate the json_type_traits |
| 414 |
|
| 415 |
The macro `JSONCONS_ALL_CTOR_GETTER_TRAITS` will generate the `json_type_traits` boilerplate |
| 416 |
for your own types from a constructor and getter functions. |
| 417 |
|
| 418 |
```cpp |
| 419 |
#include <cassert> |
| 420 |
#include <iostream> |
| 421 |
#include <jsoncons/json.hpp> |
| 422 |
|
| 423 |
namespace ns { |
| 424 |
enum class hiking_experience {beginner,intermediate,advanced}; |
| 425 |
|
| 426 |
class hiking_reputon |
| 427 |
{ |
| 428 |
std::string rater_; |
| 429 |
hiking_experience assertion_; |
| 430 |
std::string rated_; |
| 431 |
double rating_; |
| 432 |
std::optional<std::chrono::seconds> generated_; // use std::optional if C++17 |
| 433 |
std::optional<std::chrono::seconds> expires_; |
| 434 |
public: |
| 435 |
hiking_reputon(const std::string& rater, |
| 436 |
hiking_experience assertion, |
| 437 |
const std::string& rated, |
| 438 |
double rating, |
| 439 |
const std::optional<std::chrono::seconds>& generated = std::optional<std::chrono::seconds>(), |
| 440 |
const std::optional<std::chrono::seconds>& expires = std::optional<std::chrono::seconds>()) |
| 441 |
: rater_(rater), assertion_(assertion), rated_(rated), rating_(rating), |
| 442 |
generated_(generated), expires_(expires) |
| 443 |
{ |
| 444 |
} |
| 445 |
|
| 446 |
const std::string& rater() const {return rater_;} |
| 447 |
hiking_experience assertion() const {return assertion_;} |
| 448 |
const std::string& rated() const {return rated_;} |
| 449 |
double rating() const {return rating_;} |
| 450 |
std::optional<std::chrono::seconds> generated() const {return generated_;} |
| 451 |
std::optional<std::chrono::seconds> expires() const {return expires_;} |
| 452 |
|
| 453 |
friend bool operator==(const hiking_reputon& lhs, const hiking_reputon& rhs) |
| 454 |
{ |
| 455 |
return lhs.rater_ == rhs.rater_ && lhs.assertion_ == rhs.assertion_ && |
| 456 |
lhs.rated_ == rhs.rated_ && lhs.rating_ == rhs.rating_ && |
| 457 |
lhs.confidence_ == rhs.confidence_ && lhs.expires_ == rhs.expires_; |
| 458 |
} |
| 459 |
|
| 460 |
friend bool operator!=(const hiking_reputon& lhs, const hiking_reputon& rhs) |
| 461 |
{ |
| 462 |
return !(lhs == rhs); |
| 463 |
}; |
| 464 |
}; |
| 465 |
|
| 466 |
class hiking_reputation |
| 467 |
{ |
| 468 |
std::string application_; |
| 469 |
std::vector<hiking_reputon> reputons_; |
| 470 |
public: |
| 471 |
hiking_reputation(const std::string& application, |
| 472 |
const std::vector<hiking_reputon>& reputons) |
| 473 |
: application_(application), |
| 474 |
reputons_(reputons) |
| 475 |
{} |
| 476 |
|
| 477 |
const std::string& application() const { return application_;} |
| 478 |
const std::vector<hiking_reputon>& reputons() const { return reputons_;} |
| 479 |
}; |
| 480 |
|
| 481 |
} // namespace ns |
| 482 |
|
| 483 |
// Declare the traits. Specify which data members need to be serialized. |
| 484 |
|
| 485 |
JSONCONS_ENUM_TRAITS(ns::hiking_experience, beginner, intermediate, advanced) |
| 486 |
// First four members listed are mandatory, generated and expires are optional |
| 487 |
JSONCONS_N_CTOR_GETTER_TRAITS(ns::hiking_reputon, 4, rater, assertion, rated, rating, |
| 488 |
generated, expires) |
| 489 |
|
| 490 |
// All members are mandatory |
| 491 |
JSONCONS_ALL_CTOR_GETTER_TRAITS(ns::hiking_reputation, application, reputons) |
| 492 |
|
| 493 |
int main() |
| 494 |
{ |
| 495 |
// Decode the string of data into a c++ structure |
| 496 |
ns::hiking_reputation v = decode_json<ns::hiking_reputation>(data); |
| 497 |
|
| 498 |
// Iterate over reputons array value |
| 499 |
std::cout << "(1)\n"; |
| 500 |
for (const auto& item : v.reputons()) |
| 501 |
{ |
| 502 |
std::cout << item.rated() << ", " << item.rating(); |
| 503 |
if (item.generated()) |
| 504 |
{ |
| 505 |
std::cout << ", " << (*item.generated()).count(); |
| 506 |
} |
| 507 |
std::cout << "\n"; |
| 508 |
} |
| 509 |
|
| 510 |
// Encode the c++ structure into a string |
| 511 |
std::string s; |
| 512 |
encode_json_pretty(v, s); |
| 513 |
std::cout << "(2)\n"; |
| 514 |
std::cout << s << "\n"; |
| 515 |
} |
| 516 |
``` |
| 517 |
Output: |
| 518 |
``` |
| 519 |
(1) |
| 520 |
Marilyn C, 0.9, 1514862245 |
| 521 |
(2) |
| 522 |
{ |
| 523 |
"application": "hiking", |
| 524 |
"reputons": [ |
| 525 |
{ |
| 526 |
"assertion": "advanced", |
| 527 |
"generated": 1514862245, |
| 528 |
"rated": "Marilyn C", |
| 529 |
"rater": "HikingAsylum", |
| 530 |
"rating": 0.9 |
| 531 |
} |
| 532 |
] |
| 533 |
} |
| 534 |
``` |
| 535 |
|
| 536 |
<div id="A3"/> |
| 537 |
|
| 538 |
#### Example with std::shared_ptr, std::unique_ptr and std::optional |
| 539 |
|
| 540 |
This example assumes C++17 language support for `std::optional`. |
| 541 |
Lacking that, you can use `jsoncons::optional`. |
| 542 |
|
| 543 |
```cpp |
| 544 |
#include <cassert> |
| 545 |
#include <iostream> |
| 546 |
#include <jsoncons/json.hpp> |
| 547 |
|
| 548 |
namespace ns { |
| 549 |
struct smart_pointer_and_optional_test |
| 550 |
{ |
| 551 |
std::shared_ptr<std::string> field1; |
| 552 |
std::unique_ptr<std::string> field2; |
| 553 |
std::optional<std::string> field3; |
| 554 |
std::shared_ptr<std::string> field4; |
| 555 |
std::unique_ptr<std::string> field5; |
| 556 |
std::optional<std::string> field6; |
| 557 |
std::shared_ptr<std::string> field7; |
| 558 |
std::unique_ptr<std::string> field8; |
| 559 |
std::optional<std::string> field9; |
| 560 |
std::shared_ptr<std::string> field10; |
| 561 |
std::unique_ptr<std::string> field11; |
| 562 |
std::optional<std::string> field12; |
| 563 |
}; |
| 564 |
|
| 565 |
} // namespace ns |
| 566 |
|
| 567 |
// Declare the traits, first 6 members mandatory, last 6 non-mandatory |
| 568 |
JSONCONS_N_MEMBER_TRAITS(ns::smart_pointer_and_optional_test,6, |
| 569 |
field1,field2,field3,field4,field5,field6, |
| 570 |
field7,field8,field9,field10,field11,field12) |
| 571 |
|
| 572 |
using namespace jsoncons; // for convenience |
| 573 |
|
| 574 |
int main() |
| 575 |
{ |
| 576 |
ns::smart_pointer_and_optional_test val; |
| 577 |
val.field1 = std::make_shared<std::string>("Field 1"); |
| 578 |
val.field2 = jsoncons::make_unique<std::string>("Field 2"); |
| 579 |
val.field3 = "Field 3"; |
| 580 |
val.field4 = std::shared_ptr<std::string>(nullptr); |
| 581 |
val.field5 = std::unique_ptr<std::string>(nullptr); |
| 582 |
val.field6 = std::optional<std::string>(); |
| 583 |
val.field7 = std::make_shared<std::string>("Field 7"); |
| 584 |
val.field8 = jsoncons::make_unique<std::string>("Field 8"); |
| 585 |
val.field9 = "Field 9"; |
| 586 |
val.field10 = std::shared_ptr<std::string>(nullptr); |
| 587 |
val.field11 = std::unique_ptr<std::string>(nullptr); |
| 588 |
val.field12 = std::optional<std::string>(); |
| 589 |
|
| 590 |
std::string buf; |
| 591 |
encode_json(val, buf, indenting::indent); |
| 592 |
std::cout << buf << "\n"; |
| 593 |
|
| 594 |
auto other = decode_json<ns::smart_pointer_and_optional_test>(buf); |
| 595 |
|
| 596 |
assert(*other.field1 == *val.field1); |
| 597 |
assert(*other.field2 == *val.field2); |
| 598 |
assert(*other.field3 == *val.field3); |
| 599 |
assert(!other.field4); |
| 600 |
assert(!other.field5); |
| 601 |
assert(!other.field6); |
| 602 |
assert(*other.field7 == *val.field7); |
| 603 |
assert(*other.field8 == *val.field8); |
| 604 |
assert(*other.field9 == *val.field9); |
| 605 |
assert(!other.field10); |
| 606 |
assert(!other.field11); |
| 607 |
assert(!other.field12); |
| 608 |
} |
| 609 |
``` |
| 610 |
Output: |
| 611 |
``` |
| 612 |
{ |
| 613 |
"field1": "Field 1", |
| 614 |
"field2": "Field 2", |
| 615 |
"field3": "Field 3", |
| 616 |
"field4": null, |
| 617 |
"field5": null, |
| 618 |
"field6": null, |
| 619 |
"field7": "Field 7", |
| 620 |
"field8": "Field 8", |
| 621 |
"field9": "Field 9" |
| 622 |
} |
| 623 |
``` |
| 624 |
|
| 625 |
<div id="A4"/> |
| 626 |
|
| 627 |
#### Serialize a polymorphic type based on the presence of members |
| 628 |
|
| 629 |
This example uses the convenience macro `JSONCONS_N_CTOR_GETTER_TRAITS` |
| 630 |
to generate the `json_type_traits` boilerplate for the `HourlyEmployee` and `CommissionedEmployee` |
| 631 |
derived classes, and `JSONCONS_POLYMORPHIC_TRAITS` to generate the `json_type_traits` boilerplate |
| 632 |
for `std::shared_ptr<Employee>` and `std::unique_ptr<Employee>`. The type selection strategy is based |
| 633 |
on the presence of mandatory members, in particular, to the `firstName`, `lastName`, and `wage` members of an |
| 634 |
`HourlyEmployee`, and to the `firstName`, `lastName`, `baseSalary`, and `commission` members of a `CommissionedEmployee`. |
| 635 |
Non-mandatory members are not considered for the purpose of type selection. |
| 636 |
|
| 637 |
```cpp |
| 638 |
#include <cassert> |
| 639 |
#include <iostream> |
| 640 |
#include <vector> |
| 641 |
#include <jsoncons/json.hpp> |
| 642 |
|
| 643 |
using namespace jsoncons; |
| 644 |
|
| 645 |
namespace ns { |
| 646 |
|
| 647 |
class Employee |
| 648 |
{ |
| 649 |
std::string firstName_; |
| 650 |
std::string lastName_; |
| 651 |
public: |
| 652 |
Employee(const std::string& firstName, const std::string& lastName) |
| 653 |
: firstName_(firstName), lastName_(lastName) |
| 654 |
{ |
| 655 |
} |
| 656 |
virtual ~Employee() noexcept = default; |
| 657 |
|
| 658 |
virtual double calculatePay() const = 0; |
| 659 |
|
| 660 |
const std::string& firstName() const {return firstName_;} |
| 661 |
const std::string& lastName() const {return lastName_;} |
| 662 |
}; |
| 663 |
|
| 664 |
class HourlyEmployee : public Employee |
| 665 |
{ |
| 666 |
double wage_; |
| 667 |
unsigned hours_; |
| 668 |
public: |
| 669 |
HourlyEmployee(const std::string& firstName, const std::string& lastName, |
| 670 |
double wage, unsigned hours) |
| 671 |
: Employee(firstName, lastName), |
| 672 |
wage_(wage), hours_(hours) |
| 673 |
{ |
| 674 |
} |
| 675 |
|
| 676 |
double wage() const {return wage_;} |
| 677 |
|
| 678 |
unsigned hours() const {return hours_;} |
| 679 |
|
| 680 |
double calculatePay() const override |
| 681 |
{ |
| 682 |
return wage_*hours_; |
| 683 |
} |
| 684 |
}; |
| 685 |
|
| 686 |
class CommissionedEmployee : public Employee |
| 687 |
{ |
| 688 |
double baseSalary_; |
| 689 |
double commission_; |
| 690 |
unsigned sales_; |
| 691 |
public: |
| 692 |
CommissionedEmployee(const std::string& firstName, const std::string& lastName, |
| 693 |
double baseSalary, double commission, unsigned sales) |
| 694 |
: Employee(firstName, lastName), |
| 695 |
baseSalary_(baseSalary), commission_(commission), sales_(sales) |
| 696 |
{ |
| 697 |
} |
| 698 |
|
| 699 |
double baseSalary() const |
| 700 |
{ |
| 701 |
return baseSalary_; |
| 702 |
} |
| 703 |
|
| 704 |
double commission() const |
| 705 |
{ |
| 706 |
return commission_; |
| 707 |
} |
| 708 |
|
| 709 |
unsigned sales() const |
| 710 |
{ |
| 711 |
return sales_; |
| 712 |
} |
| 713 |
|
| 714 |
double calculatePay() const override |
| 715 |
{ |
| 716 |
return baseSalary_ + commission_*sales_; |
| 717 |
} |
| 718 |
}; |
| 719 |
|
| 720 |
} // ns |
| 721 |
|
| 722 |
JSONCONS_N_CTOR_GETTER_TRAITS(ns::HourlyEmployee, 3, firstName, lastName, wage, hours) |
| 723 |
JSONCONS_N_CTOR_GETTER_TRAITS(ns::CommissionedEmployee, 4, firstName, lastName, baseSalary, commission, sales) |
| 724 |
JSONCONS_POLYMORPHIC_TRAITS(ns::Employee, ns::HourlyEmployee, ns::CommissionedEmployee) |
| 725 |
|
| 726 |
int main() |
| 727 |
{ |
| 728 |
std::string input = R"( |
| 729 |
[ |
| 730 |
{ |
| 731 |
"firstName": "John", |
| 732 |
"hours": 1000, |
| 733 |
"lastName": "Smith", |
| 734 |
"wage": 40.0 |
| 735 |
}, |
| 736 |
{ |
| 737 |
"baseSalary": 30000.0, |
| 738 |
"commission": 0.25, |
| 739 |
"firstName": "Jane", |
| 740 |
"lastName": "Doe", |
| 741 |
"sales": 1000 |
| 742 |
} |
| 743 |
] |
| 744 |
)"; |
| 745 |
|
| 746 |
auto v = decode_json<std::vector<std::unique_ptr<ns::Employee>>>(input); |
| 747 |
|
| 748 |
std::cout << "(1)\n"; |
| 749 |
for (const auto& p : v) |
| 750 |
{ |
| 751 |
std::cout << p->firstName() << " " << p->lastName() << ", " << p->calculatePay() << "\n"; |
| 752 |
} |
| 753 |
|
| 754 |
std::cout << "\n(2)\n"; |
| 755 |
encode_json(v, std::cout, indenting::indent); |
| 756 |
|
| 757 |
std::cout << "\n\n(3)\n"; |
| 758 |
json j(v); |
| 759 |
std::cout << pretty_print(j) << "\n\n"; |
| 760 |
} |
| 761 |
``` |
| 762 |
Output: |
| 763 |
``` |
| 764 |
(1) |
| 765 |
John Smith, 40000 |
| 766 |
Jane Doe, 30250 |
| 767 |
|
| 768 |
(2) |
| 769 |
[ |
| 770 |
{ |
| 771 |
"firstName": "John", |
| 772 |
"hours": 1000, |
| 773 |
"lastName": "Smith", |
| 774 |
"wage": 40.0 |
| 775 |
}, |
| 776 |
{ |
| 777 |
"baseSalary": 30000.0, |
| 778 |
"commission": 0.25, |
| 779 |
"firstName": "Jane", |
| 780 |
"lastName": "Doe", |
| 781 |
"sales": 1000 |
| 782 |
} |
| 783 |
] |
| 784 |
|
| 785 |
(3) |
| 786 |
[ |
| 787 |
{ |
| 788 |
"firstName": "John", |
| 789 |
"hours": 1000, |
| 790 |
"lastName": "Smith", |
| 791 |
"wage": 40.0 |
| 792 |
}, |
| 793 |
{ |
| 794 |
"baseSalary": 30000.0, |
| 795 |
"commission": 0.25, |
| 796 |
"firstName": "Jane", |
| 797 |
"lastName": "Doe", |
| 798 |
"sales": 1000 |
| 799 |
} |
| 800 |
] |
| 801 |
``` |
| 802 |
|
| 803 |
<div id="A5"/> |
| 804 |
|
| 805 |
#### Ensuring type selection is possible |
| 806 |
|
| 807 |
When deserializing a polymorphic type, jsoncons needs to know how |
| 808 |
to convert a json value to the proper derived class. In the Employee |
| 809 |
example above, the type selection strategy is based |
| 810 |
on the presence of members in the derived classes. If |
| 811 |
derived classes cannot be distinguished in this way, |
| 812 |
you can introduce extra members. The convenience |
| 813 |
macros `JSONCONS_N_MEMBER_TRAITS`, `JSONCONS_ALL_MEMBER_TRAITS`, |
| 814 |
`JSONCONS_TPL_N_MEMBER_TRAITS`, `JSONCONS_TPL_ALL_MEMBER_TRAITS`, |
| 815 |
`JSONCONS_N_MEMBER_NAME_TRAITS`, `JSONCONS_ALL_MEMBER_NAME_TRAITS`, |
| 816 |
`JSONCONS_TPL_N_MEMBER_NAME_TRAITS`, and `JSONCONS_TPL_ALL_MEMBER_NAME_TRAITS` |
| 817 |
allow you to have `const` or `static const` data members that are serialized and that |
| 818 |
particpate in the type selection strategy during deserialization. |
| 819 |
|
| 820 |
```cpp |
| 821 |
namespace ns { |
| 822 |
|
| 823 |
class Foo |
| 824 |
{ |
| 825 |
public: |
| 826 |
virtual ~Foo() noexcept = default; |
| 827 |
}; |
| 828 |
|
| 829 |
class Bar : public Foo |
| 830 |
{ |
| 831 |
static const bool bar = true; |
| 832 |
JSONCONS_TYPE_TRAITS_FRIEND |
| 833 |
}; |
| 834 |
|
| 835 |
class Baz : public Foo |
| 836 |
{ |
| 837 |
static const bool baz = true; |
| 838 |
JSONCONS_TYPE_TRAITS_FRIEND |
| 839 |
}; |
| 840 |
|
| 841 |
} // ns |
| 842 |
|
| 843 |
JSONCONS_N_MEMBER_TRAITS(ns::Bar,1,bar) |
| 844 |
JSONCONS_N_MEMBER_TRAITS(ns::Baz,1,baz) |
| 845 |
JSONCONS_POLYMORPHIC_TRAITS(ns::Foo, ns::Bar, ns::Baz) |
| 846 |
|
| 847 |
int main() |
| 848 |
{ |
| 849 |
std::vector<std::unique_ptr<ns::Foo>> u; |
| 850 |
u.emplace_back(new ns::Bar()); |
| 851 |
u.emplace_back(new ns::Baz()); |
| 852 |
|
| 853 |
std::string buffer; |
| 854 |
encode_json(u, buffer); |
| 855 |
std::cout << "(1)\n" << buffer << "\n\n"; |
| 856 |
|
| 857 |
auto v = decode_json<std::vector<std::unique_ptr<ns::Foo>>>(buffer); |
| 858 |
|
| 859 |
std::cout << "(2)\n"; |
| 860 |
for (const auto& ptr : v) |
| 861 |
{ |
| 862 |
if (dynamic_cast<ns::Bar*>(ptr.get())) |
| 863 |
{ |
| 864 |
std::cout << "A bar\n"; |
| 865 |
} |
| 866 |
else if (dynamic_cast<ns::Baz*>(ptr.get())) |
| 867 |
{ |
| 868 |
std::cout << "A baz\n"; |
| 869 |
} |
| 870 |
} |
| 871 |
} |
| 872 |
``` |
| 873 |
|
| 874 |
Output: |
| 875 |
``` |
| 876 |
(1) |
| 877 |
[{"bar":true},{"baz":true}] |
| 878 |
|
| 879 |
(2) |
| 880 |
A bar |
| 881 |
A baz |
| 882 |
``` |
| 883 |
|
| 884 |
<div id="A6"/> |
| 885 |
|
| 886 |
#### Decode to a polymorphic type based on a type marker (since 0.157.0) |
| 887 |
|
| 888 |
```cpp |
| 889 |
namespace ns { |
| 890 |
|
| 891 |
class Shape |
| 892 |
{ |
| 893 |
public: |
| 894 |
virtual ~Shape() = default; |
| 895 |
virtual double area() const = 0; |
| 896 |
}; |
| 897 |
|
| 898 |
class Rectangle : public Shape |
| 899 |
{ |
| 900 |
double height_; |
| 901 |
double width_; |
| 902 |
public: |
| 903 |
Rectangle(double height, double width) |
| 904 |
: height_(height), width_(width) |
| 905 |
{ |
| 906 |
} |
| 907 |
|
| 908 |
const std::string& type() const |
| 909 |
{ |
| 910 |
static const std::string type_ = "rectangle"; |
| 911 |
return type_; |
| 912 |
} |
| 913 |
|
| 914 |
double height() const |
| 915 |
{ |
| 916 |
return height_; |
| 917 |
} |
| 918 |
|
| 919 |
double width() const |
| 920 |
{ |
| 921 |
return width_; |
| 922 |
} |
| 923 |
|
| 924 |
double area() const override |
| 925 |
{ |
| 926 |
return height_ * width_; |
| 927 |
} |
| 928 |
}; |
| 929 |
|
| 930 |
class Triangle : public Shape |
| 931 |
{ |
| 932 |
double height_; |
| 933 |
double width_; |
| 934 |
|
| 935 |
public: |
| 936 |
Triangle(double height, double width) |
| 937 |
: height_(height), width_(width) |
| 938 |
{ |
| 939 |
} |
| 940 |
|
| 941 |
const std::string& type() const |
| 942 |
{ |
| 943 |
static const std::string type_ = "triangle"; |
| 944 |
return type_; |
| 945 |
} |
| 946 |
|
| 947 |
double height() const |
| 948 |
{ |
| 949 |
return height_; |
| 950 |
} |
| 951 |
|
| 952 |
double width() const |
| 953 |
{ |
| 954 |
return width_; |
| 955 |
} |
| 956 |
|
| 957 |
double area() const override |
| 958 |
{ |
| 959 |
return (height_ * width_)/2.0; |
| 960 |
} |
| 961 |
}; |
| 962 |
|
| 963 |
class Circle : public Shape |
| 964 |
{ |
| 965 |
double radius_; |
| 966 |
|
| 967 |
public: |
| 968 |
Circle(double radius) |
| 969 |
: radius_(radius) |
| 970 |
{ |
| 971 |
} |
| 972 |
|
| 973 |
const std::string& type() const |
| 974 |
{ |
| 975 |
static const std::string type_ = "circle"; |
| 976 |
return type_; |
| 977 |
} |
| 978 |
|
| 979 |
double radius() const |
| 980 |
{ |
| 981 |
return radius_; |
| 982 |
} |
| 983 |
|
| 984 |
double area() const override |
| 985 |
{ |
| 986 |
constexpr double pi = 3.14159265358979323846; |
| 987 |
return pi*radius_*radius_; |
| 988 |
} |
| 989 |
}; |
| 990 |
|
| 991 |
} // ns |
| 992 |
|
| 993 |
JSONCONS_ALL_CTOR_GETTER_NAME_TRAITS(ns::Rectangle, |
| 994 |
(type,"type",JSONCONS_RDONLY,[](const std::string& type) noexcept{return type == "rectangle";}), |
| 995 |
(height, "height"), |
| 996 |
(width, "width") |
| 997 |
) |
| 998 |
|
| 999 |
JSONCONS_ALL_CTOR_GETTER_NAME_TRAITS(ns::Triangle, |
| 1000 |
(type,"type", JSONCONS_RDONLY, [](const std::string& type) noexcept {return type == "triangle";}), |
| 1001 |
(height, "height"), |
| 1002 |
(width, "width") |
| 1003 |
) |
| 1004 |
|
| 1005 |
JSONCONS_ALL_CTOR_GETTER_NAME_TRAITS(ns::Circle, |
| 1006 |
(type,"type", JSONCONS_RDONLY, [](const std::string& type) noexcept {return type == "circle";}), |
| 1007 |
(radius, "radius") |
| 1008 |
) |
| 1009 |
|
| 1010 |
JSONCONS_POLYMORPHIC_TRAITS(ns::Shape,ns::Rectangle,ns::Triangle,ns::Circle) |
| 1011 |
|
| 1012 |
int main() |
| 1013 |
{ |
| 1014 |
std::string input = R"( |
| 1015 |
[ |
| 1016 |
{"type" : "rectangle", "width" : 2.0, "height" : 1.5 }, |
| 1017 |
{"type" : "triangle", "width" : 4.0, "height" : 2.0 }, |
| 1018 |
{"type" : "circle", "radius" : 1.0 } |
| 1019 |
] |
| 1020 |
)"; |
| 1021 |
|
| 1022 |
auto shapes = jsoncons::decode_json<std::vector<std::unique_ptr<ns::Shape>>>(input); |
| 1023 |
|
| 1024 |
std::cout << "(1)\n"; |
| 1025 |
for (const auto& shape : shapes) |
| 1026 |
{ |
| 1027 |
std::cout << typeid(*shape.get()).name() << " area: " << shape->area() << "\n"; |
| 1028 |
} |
| 1029 |
|
| 1030 |
std::string output; |
| 1031 |
|
| 1032 |
jsoncons::encode_json(shapes, output, indenting::indent); |
| 1033 |
std::cout << "\n(2)\n" << output << "\n"; |
| 1034 |
} |
| 1035 |
``` |
| 1036 |
|
| 1037 |
Output: |
| 1038 |
``` |
| 1039 |
(1) |
| 1040 |
class `ns::Rectangle area: 3.0000000 |
| 1041 |
class `ns::Triangle area: 4.0000000 |
| 1042 |
class `ns::Circle area: 3.1415927 |
| 1043 |
|
| 1044 |
(2) |
| 1045 |
[ |
| 1046 |
{ |
| 1047 |
"height": 1.5, |
| 1048 |
"type": "rectangle", |
| 1049 |
"width": 2.0 |
| 1050 |
}, |
| 1051 |
{ |
| 1052 |
"height": 2.0, |
| 1053 |
"type": "triangle", |
| 1054 |
"width": 4.0 |
| 1055 |
}, |
| 1056 |
{ |
| 1057 |
"radius": 1.0, |
| 1058 |
"type": "circle" |
| 1059 |
} |
| 1060 |
] |
| 1061 |
``` |
| 1062 |
|
| 1063 |
This example maps a `type()` getter to a "type" data member in the JSON. |
| 1064 |
However, we can also achieve this without using a `type()` getter at all. |
| 1065 |
Compare with the very similar example [decode to a std::variant based on a type marker](#A9) |
| 1066 |
|
| 1067 |
<div id="A7"/> |
| 1068 |
|
| 1069 |
#### An example with std::variant |
| 1070 |
|
| 1071 |
This example assumes C++17 language support and jsoncons v0.154.0 or later. |
| 1072 |
|
| 1073 |
```cpp |
| 1074 |
#include <jsoncons/json.hpp> |
| 1075 |
|
| 1076 |
namespace ns { |
| 1077 |
|
| 1078 |
enum class Color {yellow, red, green, blue}; |
| 1079 |
|
| 1080 |
inline |
| 1081 |
std::ostream& operator<<(std::ostream& os, Color val) |
| 1082 |
{ |
| 1083 |
switch (val) |
| 1084 |
{ |
| 1085 |
case Color::yellow: os << "yellow"; break; |
| 1086 |
case Color::red: os << "red"; break; |
| 1087 |
case Color::green: os << "green"; break; |
| 1088 |
case Color::blue: os << "blue"; break; |
| 1089 |
} |
| 1090 |
return os; |
| 1091 |
} |
| 1092 |
|
| 1093 |
class Fruit |
| 1094 |
{ |
| 1095 |
JSONCONS_TYPE_TRAITS_FRIEND |
| 1096 |
std::string name_; |
| 1097 |
Color color_; |
| 1098 |
public: |
| 1099 |
friend std::ostream& operator<<(std::ostream& os, const Fruit& val) |
| 1100 |
{ |
| 1101 |
os << "name: " << val.name_ << ", color: " << val.color_ << "\n"; |
| 1102 |
return os; |
| 1103 |
} |
| 1104 |
}; |
| 1105 |
|
| 1106 |
class Fabric |
| 1107 |
{ |
| 1108 |
JSONCONS_TYPE_TRAITS_FRIEND |
| 1109 |
int size_; |
| 1110 |
std::string material_; |
| 1111 |
public: |
| 1112 |
friend std::ostream& operator<<(std::ostream& os, const Fabric& val) |
| 1113 |
{ |
| 1114 |
os << "size: " << val.size_ << ", material: " << val.material_ << "\n"; |
| 1115 |
return os; |
| 1116 |
} |
| 1117 |
}; |
| 1118 |
|
| 1119 |
class Basket |
| 1120 |
{ |
| 1121 |
JSONCONS_TYPE_TRAITS_FRIEND |
| 1122 |
std::string owner_; |
| 1123 |
std::vector<std::variant<Fruit, Fabric>> items_; |
| 1124 |
|
| 1125 |
public: |
| 1126 |
std::string owner() const |
| 1127 |
{ |
| 1128 |
return owner_; |
| 1129 |
} |
| 1130 |
|
| 1131 |
std::vector<std::variant<Fruit, Fabric>> items() const |
| 1132 |
{ |
| 1133 |
return items_; |
| 1134 |
} |
| 1135 |
}; |
| 1136 |
|
| 1137 |
} // ns |
| 1138 |
} // namespace |
| 1139 |
|
| 1140 |
JSONCONS_ENUM_NAME_TRAITS(ns::Color, (yellow, "YELLOW"), (red, "RED"), (green, "GREEN"), (blue, "BLUE")) |
| 1141 |
|
| 1142 |
JSONCONS_ALL_MEMBER_NAME_TRAITS(ns::Fruit, |
| 1143 |
(name_, "name"), |
| 1144 |
(color_, "color")) |
| 1145 |
JSONCONS_ALL_MEMBER_NAME_TRAITS(ns::Fabric, |
| 1146 |
(size_, "size"), |
| 1147 |
(material_, "material")) |
| 1148 |
JSONCONS_ALL_MEMBER_NAME_TRAITS(ns::Basket, |
| 1149 |
(owner_, "owner"), |
| 1150 |
(items_, "items")) |
| 1151 |
|
| 1152 |
int main() |
| 1153 |
{ |
| 1154 |
std::string input = R"( |
| 1155 |
{ |
| 1156 |
"owner": "Rodrigo", |
| 1157 |
"items": [ |
| 1158 |
{ |
| 1159 |
"name": "banana", |
| 1160 |
"color": "YELLOW" |
| 1161 |
}, |
| 1162 |
{ |
| 1163 |
"size": 40, |
| 1164 |
"material": "wool" |
| 1165 |
}, |
| 1166 |
{ |
| 1167 |
"name": "apple", |
| 1168 |
"color": "RED" |
| 1169 |
}, |
| 1170 |
{ |
| 1171 |
"size": 40, |
| 1172 |
"material": "cotton" |
| 1173 |
} |
| 1174 |
] |
| 1175 |
} |
| 1176 |
)"; |
| 1177 |
|
| 1178 |
ns::Basket basket = jsoncons::decode_json<ns::Basket>(input); |
| 1179 |
std::cout << basket.owner() << "\n\n"; |
| 1180 |
|
| 1181 |
std::cout << "(1)\n"; |
| 1182 |
for (const auto& var : basket.items()) |
| 1183 |
{ |
| 1184 |
std::visit([](auto&& arg) { |
| 1185 |
using T = std::decay_t<decltype(arg)>; |
| 1186 |
if constexpr (std::is_same_v<T, ns::Fruit>) |
| 1187 |
std::cout << "Fruit " << arg << '\n'; |
| 1188 |
else if constexpr (std::is_same_v<T, ns::Fabric>) |
| 1189 |
std::cout << "Fabric " << arg << '\n'; |
| 1190 |
}, var); |
| 1191 |
} |
| 1192 |
|
| 1193 |
std::string output; |
| 1194 |
jsoncons::encode_json(basket, output, indenting::indent); |
| 1195 |
std::cout << "(2)\n" << output << "\n\n"; |
| 1196 |
} |
| 1197 |
``` |
| 1198 |
Output: |
| 1199 |
``` |
| 1200 |
Rodrigo |
| 1201 |
|
| 1202 |
(1) |
| 1203 |
Fruit name: banana, color: yellow |
| 1204 |
|
| 1205 |
Fabric size: 28, material: wool |
| 1206 |
|
| 1207 |
Fruit name: apple, color: red |
| 1208 |
|
| 1209 |
Fabric size: 28, material: cotton |
| 1210 |
|
| 1211 |
(2) |
| 1212 |
{ |
| 1213 |
"items": [ |
| 1214 |
{ |
| 1215 |
"color": "YELLOW", |
| 1216 |
"name": "banana" |
| 1217 |
}, |
| 1218 |
{ |
| 1219 |
"material": "wool", |
| 1220 |
"size": 40 |
| 1221 |
}, |
| 1222 |
{ |
| 1223 |
"color": "RED", |
| 1224 |
"name": "apple" |
| 1225 |
}, |
| 1226 |
{ |
| 1227 |
"material": "cotton", |
| 1228 |
"size": 40 |
| 1229 |
} |
| 1230 |
], |
| 1231 |
"owner": "Rodrigo" |
| 1232 |
} |
| 1233 |
``` |
| 1234 |
|
| 1235 |
<div id="A8"/> |
| 1236 |
|
| 1237 |
#### Type selection and std::variant |
| 1238 |
|
| 1239 |
For classes supported through the convenience macros, e.g. `Fruit` and `Fabric` from the previous example, |
| 1240 |
the type selection strategy is the same as for polymorphic types, and is based |
| 1241 |
on the presence of mandatory members in the classes. More generally, |
| 1242 |
the type selection strategy is based on the `json_type_traits<Json,T>::is(const Json& j)` |
| 1243 |
function, checking each type in the variant from left to right, and stopping when |
| 1244 |
`json_type_traits<Json,T>::is(j)` returns **true**. |
| 1245 |
|
| 1246 |
Now consider |
| 1247 |
|
| 1248 |
```cpp |
| 1249 |
#include <jsoncons/json.hpp> |
| 1250 |
|
| 1251 |
namespace ns { |
| 1252 |
|
| 1253 |
enum class Color {yellow, red, green, blue}; |
| 1254 |
|
| 1255 |
} // ns |
| 1256 |
|
| 1257 |
JSONCONS_ENUM_NAME_TRAITS(ns::Color, (yellow, "YELLOW"), (red, "RED"), (green, "GREEN"), (blue, "BLUE")) |
| 1258 |
|
| 1259 |
int main() |
| 1260 |
{ |
| 1261 |
using variant_type = std::variant<int, double, bool, std::string, ns::Color>; |
| 1262 |
|
| 1263 |
std::vector<variant_type> vars = {100, 10.1, false, std::string("Hello World"), ns::Color::yellow}; |
| 1264 |
|
| 1265 |
std::string buffer; |
| 1266 |
jsoncons::encode_json(vars, buffer, indenting::indent); |
| 1267 |
|
| 1268 |
std::cout << "(1)\n" << buffer << "\n\n"; |
| 1269 |
|
| 1270 |
auto vars2 = jsoncons::decode_json<std::vector<variant_type>>(buffer); |
| 1271 |
|
| 1272 |
auto visitor = [](auto&& arg) { |
| 1273 |
using T = std::decay_t<decltype(arg)>; |
| 1274 |
if constexpr (std::is_same_v<T, int>) |
| 1275 |
std::cout << "int " << arg << '\n'; |
| 1276 |
else if constexpr (std::is_same_v<T, double>) |
| 1277 |
std::cout << "double " << arg << '\n'; |
| 1278 |
else if constexpr (std::is_same_v<T, bool>) |
| 1279 |
std::cout << "bool " << arg << '\n'; |
| 1280 |
else if constexpr (std::is_same_v<T, std::string>) |
| 1281 |
std::cout << "std::string " << arg << '\n'; |
| 1282 |
else if constexpr (std::is_same_v<T, ns::Color>) |
| 1283 |
std::cout << "ns::Color " << arg << '\n'; |
| 1284 |
}; |
| 1285 |
|
| 1286 |
std::cout << "(2)\n"; |
| 1287 |
for (const auto& item : vars2) |
| 1288 |
{ |
| 1289 |
std::visit(visitor, item); |
| 1290 |
} |
| 1291 |
std::cout << "\n"; |
| 1292 |
} |
| 1293 |
``` |
| 1294 |
Output: |
| 1295 |
``` |
| 1296 |
(1) |
| 1297 |
[ |
| 1298 |
100, |
| 1299 |
10.1, |
| 1300 |
false, |
| 1301 |
"Hello World", |
| 1302 |
"YELLOW" |
| 1303 |
] |
| 1304 |
|
| 1305 |
(2) |
| 1306 |
int 100 |
| 1307 |
double 10.1 |
| 1308 |
bool false |
| 1309 |
std::string Hello World |
| 1310 |
std::string YELLOW |
| 1311 |
``` |
| 1312 |
|
| 1313 |
Encode is fine. But when decoding, jsoncons checks if the JSON string "YELLOW" is a `std::string` |
| 1314 |
before it checks whether it is an `ns::Color`, and since the answer is yes, |
| 1315 |
it is stored in the variant as a `std::string`. |
| 1316 |
|
| 1317 |
But if we switch the order of `ns::Color` and `std::string` in the variant definition, viz. |
| 1318 |
|
| 1319 |
```cpp |
| 1320 |
using variant_type = std::variant<int, double, bool, ns::Color, std::string>; |
| 1321 |
``` |
| 1322 |
strings containing the text "YELLOW", "RED", "GREEN", or "BLUE" are detected to be `ns::Color`, and the others `std::string`. |
| 1323 |
|
| 1324 |
And the output becomes |
| 1325 |
``` |
| 1326 |
(1) |
| 1327 |
[ |
| 1328 |
100, |
| 1329 |
10.1, |
| 1330 |
false, |
| 1331 |
"Hello World", |
| 1332 |
"YELLOW" |
| 1333 |
] |
| 1334 |
|
| 1335 |
(2) |
| 1336 |
int 100 |
| 1337 |
double 10.1 |
| 1338 |
bool false |
| 1339 |
std::string Hello World |
| 1340 |
ns::Color yellow |
| 1341 |
``` |
| 1342 |
|
| 1343 |
So: types that are more constrained should appear to the left of types that are less constrained. |
| 1344 |
|
| 1345 |
<div id="A9"/> |
| 1346 |
|
| 1347 |
#### Decode to a std::variant based on a type marker (since 0.158.0) |
| 1348 |
|
| 1349 |
This example is very similar to [decode to a polymorphic type based on a type marker](#A6), |
| 1350 |
and in fact the json traits defined for that example would do for `std::variant` as well. |
| 1351 |
But here we add a wrinkle by omitting the `type()` function in the `Rectangle`, `Triangle` and |
| 1352 |
`Circle` classes. More generally, we show how to augment the JSON output with name/value pairs |
| 1353 |
that are not present in the class definitions, and to perform type selection with them. |
| 1354 |
|
| 1355 |
```cpp |
| 1356 |
#include <jsoncons/json.hpp> |
| 1357 |
|
| 1358 |
namespace ns { |
| 1359 |
|
| 1360 |
class Rectangle |
| 1361 |
{ |
| 1362 |
double height_; |
| 1363 |
double width_; |
| 1364 |
public: |
| 1365 |
Rectangle(double height, double width) |
| 1366 |
: height_(height), width_(width) |
| 1367 |
{ |
| 1368 |
} |
| 1369 |
|
| 1370 |
double height() const |
| 1371 |
{ |
| 1372 |
return height_; |
| 1373 |
} |
| 1374 |
|
| 1375 |
double width() const |
| 1376 |
{ |
| 1377 |
return width_; |
| 1378 |
} |
| 1379 |
|
| 1380 |
double area() const |
| 1381 |
{ |
| 1382 |
return height_ * width_; |
| 1383 |
} |
| 1384 |
}; |
| 1385 |
|
| 1386 |
class Triangle |
| 1387 |
{ |
| 1388 |
double height_; |
| 1389 |
double width_; |
| 1390 |
|
| 1391 |
public: |
| 1392 |
Triangle(double height, double width) |
| 1393 |
: height_(height), width_(width) |
| 1394 |
{ |
| 1395 |
} |
| 1396 |
|
| 1397 |
double height() const |
| 1398 |
{ |
| 1399 |
return height_; |
| 1400 |
} |
| 1401 |
|
| 1402 |
double width() const |
| 1403 |
{ |
| 1404 |
return width_; |
| 1405 |
} |
| 1406 |
|
| 1407 |
double area() const |
| 1408 |
{ |
| 1409 |
return (height_ * width_)/2.0; |
| 1410 |
} |
| 1411 |
}; |
| 1412 |
|
| 1413 |
class Circle |
| 1414 |
{ |
| 1415 |
double radius_; |
| 1416 |
|
| 1417 |
public: |
| 1418 |
Circle(double radius) |
| 1419 |
: radius_(radius) |
| 1420 |
{ |
| 1421 |
} |
| 1422 |
|
| 1423 |
double radius() const |
| 1424 |
{ |
| 1425 |
return radius_; |
| 1426 |
} |
| 1427 |
|
| 1428 |
double area() const |
| 1429 |
{ |
| 1430 |
constexpr double pi = 3.14159265358979323846; |
| 1431 |
return pi*radius_*radius_; |
| 1432 |
} |
| 1433 |
}; |
| 1434 |
|
| 1435 |
inline constexpr auto rectangle_marker = [](double) noexcept {return "rectangle"; }; |
| 1436 |
inline constexpr auto triangle_marker = [](double) noexcept {return "triangle";}; |
| 1437 |
inline constexpr auto circle_marker = [](double) noexcept {return "circle";}; |
| 1438 |
|
| 1439 |
} // namespace ns |
| 1440 |
|
| 1441 |
JSONCONS_ALL_CTOR_GETTER_NAME_TRAITS(ns::Rectangle, |
| 1442 |
(height,"type",JSONCONS_RDONLY, |
| 1443 |
[](const std::string& type) noexcept{return type == "rectangle";}, |
| 1444 |
ns::rectangle_marker), |
| 1445 |
(height, "height"), |
| 1446 |
(width, "width") |
| 1447 |
) |
| 1448 |
|
| 1449 |
JSONCONS_ALL_CTOR_GETTER_NAME_TRAITS(ns::Triangle, |
| 1450 |
(height,"type", JSONCONS_RDONLY, |
| 1451 |
[](const std::string& type) noexcept {return type == "triangle";}, |
| 1452 |
ns::triangle_marker), |
| 1453 |
(height, "height"), |
| 1454 |
(width, "width") |
| 1455 |
) |
| 1456 |
|
| 1457 |
JSONCONS_ALL_CTOR_GETTER_NAME_TRAITS(ns::Circle, |
| 1458 |
(radius,"type", JSONCONS_RDONLY, |
| 1459 |
[](const std::string& type) noexcept {return type == "circle";}, |
| 1460 |
ns::circle_marker), |
| 1461 |
(radius, "radius") |
| 1462 |
) |
| 1463 |
|
| 1464 |
int main() |
| 1465 |
{ |
| 1466 |
using shapes_t = std::variant<ns::Rectangle,ns::Triangle,ns::Circle>; |
| 1467 |
|
| 1468 |
std::string input = R"( |
| 1469 |
[ |
| 1470 |
{"type" : "rectangle", "width" : 2.0, "height" : 1.5 }, |
| 1471 |
{"type" : "triangle", "width" : 4.0, "height" : 2.0 }, |
| 1472 |
{"type" : "circle", "radius" : 1.0 } |
| 1473 |
] |
| 1474 |
)"; |
| 1475 |
|
| 1476 |
auto shapes = jsoncons::decode_json<std::vector<shapes_t>>(input); |
| 1477 |
|
| 1478 |
auto visitor = [](auto&& shape) { |
| 1479 |
using T = std::decay_t<decltype(shape)>; |
| 1480 |
if constexpr (std::is_same_v<T, ns::Rectangle>) |
| 1481 |
std::cout << "rectangle area: " << shape.area() << '\n'; |
| 1482 |
else if constexpr (std::is_same_v<T, ns::Triangle>) |
| 1483 |
std::cout << "triangle area: " << shape.area() << '\n'; |
| 1484 |
else if constexpr (std::is_same_v<T, ns::Circle>) |
| 1485 |
std::cout << "circle area: " << shape.area() << '\n'; |
| 1486 |
}; |
| 1487 |
|
| 1488 |
std::cout << "(1)\n"; |
| 1489 |
for (const auto& shape : shapes) |
| 1490 |
{ |
| 1491 |
std::visit(visitor, shape); |
| 1492 |
} |
| 1493 |
|
| 1494 |
std::string output; |
| 1495 |
jsoncons::encode_json(shapes, output, indenting::indent); |
| 1496 |
std::cout << "\n(2)\n" << output << "\n"; |
| 1497 |
} |
| 1498 |
``` |
| 1499 |
Output: |
| 1500 |
``` |
| 1501 |
(1) |
| 1502 |
rectangle area: 3.0000000 |
| 1503 |
triangle area: 4.0000000 |
| 1504 |
circle area: 3.1415927 |
| 1505 |
|
| 1506 |
(2) |
| 1507 |
[ |
| 1508 |
{ |
| 1509 |
"height": 1.5, |
| 1510 |
"type": "rectangle", |
| 1511 |
"width": 2.0 |
| 1512 |
}, |
| 1513 |
{ |
| 1514 |
"height": 2.0, |
| 1515 |
"type": "triangle", |
| 1516 |
"width": 4.0 |
| 1517 |
}, |
| 1518 |
{ |
| 1519 |
"radius": 1.0, |
| 1520 |
"type": "circle" |
| 1521 |
} |
| 1522 |
] |
| 1523 |
``` |
| 1524 |
|
| 1525 |
Note the mapping to the "type" member, in particular, for the rectangle, |
| 1526 |
|
| 1527 |
```cpp |
| 1528 |
(height,"type",JSONCONS_RDONLY, |
| 1529 |
[](const std::string& type) noexcept{return type == "rectangle";}, |
| 1530 |
ns::rectangle_marker), |
| 1531 |
``` |
| 1532 |
|
| 1533 |
There are two things to observe. First, the class member being mapped, |
| 1534 |
here `height`, can be any member, we don't actually use it. Instead, |
| 1535 |
we use the function object `ns::rectangle_marker` to ouput the value |
| 1536 |
"rectangle" with the key "type". Second, the function argument in |
| 1537 |
this position cannot be a lambda expression (at least until C++20), |
| 1538 |
because jsoncons uses it in an unevaluated context, so it is |
| 1539 |
provided as a variable containing a lambda expression instead. |
| 1540 |
|
| 1541 |
<div id="A10"/> |
| 1542 |
|
| 1543 |
#### Transform data member (since 0.158.0) |
| 1544 |
|
| 1545 |
```cpp |
| 1546 |
#include <cassert> |
| 1547 |
#include <jsoncons/json.hpp> |
| 1548 |
|
| 1549 |
namespace ns { |
| 1550 |
|
| 1551 |
class Employee |
| 1552 |
{ |
| 1553 |
std::string name_; |
| 1554 |
std::string surname_; |
| 1555 |
public: |
| 1556 |
Employee() = default; |
| 1557 |
|
| 1558 |
Employee(const std::string& name, const std::string& surname) |
| 1559 |
: name_(name), surname_(surname) |
| 1560 |
{ |
| 1561 |
} |
| 1562 |
|
| 1563 |
std::string getName() const |
| 1564 |
{ |
| 1565 |
return name_; |
| 1566 |
} |
| 1567 |
void setName(const std::string& name) |
| 1568 |
{ |
| 1569 |
name_ = name; |
| 1570 |
} |
| 1571 |
std::string getSurname()const |
| 1572 |
{ |
| 1573 |
return surname_; |
| 1574 |
} |
| 1575 |
void setSurname(const std::string& surname) |
| 1576 |
{ |
| 1577 |
surname_ = surname; |
| 1578 |
} |
| 1579 |
|
| 1580 |
friend bool operator<(const Employee& lhs, const Employee& rhs) |
| 1581 |
{ |
| 1582 |
if (lhs.surname_ < rhs.surname_) |
| 1583 |
return true; |
| 1584 |
return lhs.name_ < rhs.name_; |
| 1585 |
} |
| 1586 |
}; |
| 1587 |
|
| 1588 |
class Company |
| 1589 |
{ |
| 1590 |
std::string name_; |
| 1591 |
std::vector<uint64_t> employeeIds_; |
| 1592 |
public: |
| 1593 |
std::string getName() const |
| 1594 |
{ |
| 1595 |
return name_; |
| 1596 |
} |
| 1597 |
void setName(const std::string& name) |
| 1598 |
{ |
| 1599 |
name_ = name; |
| 1600 |
} |
| 1601 |
const std::vector<uint64_t> getIds() const |
| 1602 |
{ |
| 1603 |
return employeeIds_; |
| 1604 |
} |
| 1605 |
void setIds(const std::vector<uint64_t>& employeeIds) |
| 1606 |
{ |
| 1607 |
employeeIds_ = employeeIds; |
| 1608 |
} |
| 1609 |
}; |
| 1610 |
|
| 1611 |
std::vector<uint64_t> fromEmployeesToIds(const std::vector<Employee>& employees) |
| 1612 |
{ |
| 1613 |
static std::map<Employee, uint64_t> employee_id_map = {{Employee("John", "Smith"), 1},{Employee("Jane", "Doe"), 2}}; |
| 1614 |
|
| 1615 |
std::vector<uint64_t> ids; |
| 1616 |
for (const auto& employee : employees) |
| 1617 |
{ |
| 1618 |
ids.push_back(employee_id_map.at(employee)); |
| 1619 |
} |
| 1620 |
return ids; |
| 1621 |
} |
| 1622 |
|
| 1623 |
std::vector<Employee> toEmployeesFromIds(const std::vector<uint64_t>& ids) |
| 1624 |
{ |
| 1625 |
static std::map<uint64_t, Employee> id_employee_map = {{1, Employee("John", "Smith")},{2, Employee("Jane", "Doe")}}; |
| 1626 |
|
| 1627 |
std::vector<Employee> employees; |
| 1628 |
for (auto id : ids) |
| 1629 |
{ |
| 1630 |
employees.push_back(id_employee_map.at(id)); |
| 1631 |
} |
| 1632 |
return employees; |
| 1633 |
} |
| 1634 |
|
| 1635 |
} // namespace ns |
| 1636 |
|
| 1637 |
JSONCONS_ALL_GETTER_SETTER_NAME_TRAITS(ns::Employee, |
| 1638 |
(getName, setName, "employee_name"), |
| 1639 |
(getSurname, setSurname, "employee_surname") |
| 1640 |
) |
| 1641 |
|
| 1642 |
JSONCONS_ALL_GETTER_SETTER_NAME_TRAITS(ns::Company, |
| 1643 |
(getName, setName, "company"), |
| 1644 |
(getIds, setIds, "resources", |
| 1645 |
JSONCONS_RDWR, jsoncons::always_true(), |
| 1646 |
ns::toEmployeesFromIds, ns::fromEmployeesToIds) |
| 1647 |
) |
| 1648 |
|
| 1649 |
int main() |
| 1650 |
{ |
| 1651 |
std::string input = R"( |
| 1652 |
{ |
| 1653 |
"company": "ExampleInc", |
| 1654 |
"resources": [ |
| 1655 |
{ |
| 1656 |
"employee_name": "John", |
| 1657 |
"employee_surname": "Smith" |
| 1658 |
}, |
| 1659 |
{ |
| 1660 |
"employee_name": "Jane", |
| 1661 |
"employee_surname": "Doe" |
| 1662 |
} |
| 1663 |
] |
| 1664 |
} |
| 1665 |
)"; |
| 1666 |
|
| 1667 |
auto company = decode_json<ns::Company>(input); |
| 1668 |
|
| 1669 |
std::cout << "(1)\n" << company.getName() << "\n"; |
| 1670 |
for (auto id : company.getIds()) |
| 1671 |
{ |
| 1672 |
std::cout << id << "\n"; |
| 1673 |
} |
| 1674 |
std::cout << "\n"; |
| 1675 |
|
| 1676 |
std::string output; |
| 1677 |
encode_json_pretty(company, output); |
| 1678 |
std::cout << "(2)\n" << output << "\n\n"; |
| 1679 |
} |
| 1680 |
``` |
| 1681 |
|
| 1682 |
Output: |
| 1683 |
|
| 1684 |
``` |
| 1685 |
(1) |
| 1686 |
ExampleInc |
| 1687 |
1 |
| 1688 |
2 |
| 1689 |
|
| 1690 |
(2) |
| 1691 |
{ |
| 1692 |
"company": "ExampleInc", |
| 1693 |
"resources": [ |
| 1694 |
{ |
| 1695 |
"employee_name": "John", |
| 1696 |
"employee_surname": "Smith" |
| 1697 |
}, |
| 1698 |
{ |
| 1699 |
"employee_name": "Jane", |
| 1700 |
"employee_surname": "Doe" |
| 1701 |
} |
| 1702 |
] |
| 1703 |
} |
| 1704 |
``` |
| 1705 |
|
| 1706 |
<div id="A11"/> |
| 1707 |
|
| 1708 |
#### Tidy data member (since 0.158.0) |
| 1709 |
|
| 1710 |
```cpp |
| 1711 |
#include <jsoncons/json.hpp> |
| 1712 |
|
| 1713 |
namespace ns { |
| 1714 |
|
| 1715 |
class Person |
| 1716 |
{ |
| 1717 |
std::string name_; |
| 1718 |
std::optional<std::string> socialSecurityNumber_; |
| 1719 |
public: |
| 1720 |
Person(const std::string& name, const std::optional<std::string>& socialSecurityNumber) |
| 1721 |
: name_(name), socialSecurityNumber_(socialSecurityNumber) |
| 1722 |
{ |
| 1723 |
} |
| 1724 |
std::string getName() const |
| 1725 |
{ |
| 1726 |
return name_; |
| 1727 |
} |
| 1728 |
std::optional<std::string> getSsn() const |
| 1729 |
{ |
| 1730 |
return socialSecurityNumber_; |
| 1731 |
} |
| 1732 |
}; |
| 1733 |
|
| 1734 |
} // namespace ns |
| 1735 |
|
| 1736 |
JSONCONS_ALL_CTOR_GETTER_NAME_TRAITS(ns::Person, |
| 1737 |
(getName, "name"), |
| 1738 |
(getSsn, "social_security_number", |
| 1739 |
jsoncons::always_true(), |
| 1740 |
jsoncons::identity(), // or std::identity() if C++20 |
| 1741 |
[] (const std::optional<std::string>& unvalidated) { |
| 1742 |
if (!unvalidated) |
| 1743 |
{ |
| 1744 |
return unvalidated; |
| 1745 |
} |
| 1746 |
std::regex myRegex(("^(\\d{9})$")); |
| 1747 |
if (!std::regex_match(*unvalidated, myRegex) ) { |
| 1748 |
return std::optional<std::string>(); |
| 1749 |
} |
| 1750 |
return unvalidated; |
| 1751 |
} |
| 1752 |
) |
| 1753 |
) |
| 1754 |
|
| 1755 |
int main() |
| 1756 |
{ |
| 1757 |
std::string input = R"( |
| 1758 |
[ |
| 1759 |
{ |
| 1760 |
"name": "John Smith", |
| 1761 |
"social_security_number": "123456789" |
| 1762 |
}, |
| 1763 |
{ |
| 1764 |
"name": "Jane Doe", |
| 1765 |
"social_security_number": "12345678" |
| 1766 |
} |
| 1767 |
] |
| 1768 |
)"; |
| 1769 |
|
| 1770 |
auto persons = jsoncons::decode_json<std::vector<ns::Person>>(input); |
| 1771 |
|
| 1772 |
std::cout << "(1)\n"; |
| 1773 |
for (const auto& person : persons) |
| 1774 |
{ |
| 1775 |
std::cout << person.getName() << ", " |
| 1776 |
<< (person.getSsn() ? *person.getSsn() : "n/a") << "\n"; |
| 1777 |
} |
| 1778 |
std::cout << "\n"; |
| 1779 |
|
| 1780 |
std::string output; |
| 1781 |
jsoncons::encode_json_pretty(persons, output); |
| 1782 |
std::cout << "(2)\n" << output << "\n"; |
| 1783 |
} |
| 1784 |
``` |
| 1785 |
Output: |
| 1786 |
``` |
| 1787 |
(1) |
| 1788 |
John Smith, 123456789 |
| 1789 |
Jane Doe, n/a |
| 1790 |
|
| 1791 |
(2) |
| 1792 |
[ |
| 1793 |
{ |
| 1794 |
"name": "John Smith", |
| 1795 |
"social_security_number": "123456789" |
| 1796 |
}, |
| 1797 |
{ |
| 1798 |
"name": "Jane Doe", |
| 1799 |
"social_security_number": null |
| 1800 |
} |
| 1801 |
] |
| 1802 |
``` |