![]() |
DAW JSON Link
|
Variant or sum types are where the json member can have more than one type(like string, number, class, or array). JSON Link supports several forms of variant types
json { "type": 1, "value": [] }
where "value"
's type is determined by "type"
json { "obj": { "type": 1 } }
where "type" determines how the class itself will be parsedTake the following JSON array:
Here we have an array of a class that has two members. A variant of types number and string, member0; and a variant of type string and bool, member1.
Too see a working example using this code, refer to cookbook_variant1_test.cpp
The following C++ can provide a mapping. It, also, highlights that the types bool, integers, floating point, std:: string, and previously mapped types can be default mapped to elements that do not require a name. Such as variant, array, and some key_value's.
The elements in the json_variant_type_list
must have matching types in the variant alternatives. (e.g. std::string -> json_string, bool -> json_bool )
It is common to have a tag discriminator in JSON data. The json_tagged_variant
member type allows using another parsed member to return an index in a member list to parse. This allows any number of types to be inside the variant.
Below is a JSON array, containing a variant element where the "type"
member determines the type of the "value"
member. In many JSON documents, the discriminator will be a string.
A member name and a callable are needed to tell the parser which type will parsed.
Too see a working example using this code, refer to cookbook_variant2_test.cpp
In the above example, two members are mapped to construct MyClass, "name"
and "value"
. The variant uses the JSON "type"
member to determine the index of the parser to use for the variant value.
Extending the previous example, it auto detected the std::string
, int
, and bool
types and supplied the parser descriptions for them. Lets do it manually.
Below is a JSON array, containing a variant element where the "type"
member determines the type of the "value"
member. In many JSON documents, the discriminator will be a string.
A member name and a Callable are needed to tell the parser which type will parsed.
Too see a working example using this code, refer to cookbook_variant3_test.cpp
As you can see, the json_variant_type_list can use terse type names for some, or the full names.
There are cases where a classes structure is determined by one of it's submembers. This comes up with file versioning.
In our example we have two versions of a config file. The tag member "version"
determines the layout of the other members in the example.
The above example shows two distinct JSON objects that both have a "version"
member that is a discriminator for the expected data structure.