BDE 4.14.0 Production release
|
Provide a JSON encoder for bdlat
-compatible types.
bdlat
-compliant typesThis component provides a class, baljsn::Encoder
, for encoding value-semantic objects in the JSON format. In particular, the class
contains a parameterized encode
function that encodes an object into a specified stream. There are two overloaded versions of this function:
bsl::streambuf
bsl::ostream
This component can be used with types that support the bdlat
framework (see the bdlat
package for details), which is a compile-time interface for manipulating struct-like and union-like objects. In particular, types generated by the bas_codegen.pl
tool, and other dynamic types, can be encoded using this class
. The encode
function can be invoked on any object that satisfies the requirements of a sequence, choice, or array object as defined in the bdlat_sequencefunctions , bdlat_choicefunctions , and bdlat_arrayfunctions components.
Although the JSON format is easy to read and write and is very useful for debugging, it is relatively expensive to encode and decode and relatively bulky to transmit. It is more efficient to use a binary encoding (such as BER) if the encoding format is under your control (see balber_berencoder ).
Refer to the details of the JSON encoding format supported by this encoder in the package documentation file (doc/baljsn.txt).
This section illustrates intended use of this component.
Consider that we want to exchange an employee's information between two processes. To allow this information exchange we will define the XML schema representation for that class, use bas_codegen.pl
to create the Employee
class
for storing that information, populate an Employee
object, and encode that object using the baljsn
encoder.
First, we will define the XML schema inside a file called employee.xsd
:
Then, we will use the bas_codegen.pl
tool, to generate the C++ classes for this schema. The following command will generate the header and implementation files for the all the classes in the test_messages components in the current directory:
Next, we will populate a test::Employee
object:
Then, we will create a baljsn::Encoder
object:
Now, we will output this object in the JSON format by invoking the encode
method of the encoder. We will also create a baljsn::EncoderOptions
object that allows us to specify that the encoding should be done in a pretty format, and what the initial indent level and spaces per level should be. We will then pass that object to the encode
method:
Finally, we will verify that the output is as expected: