BDE 4.14.0 Production release
Loading...
Searching...
No Matches
baljsn_printutil

Detailed Description

Outline

Purpose

Provide a utility for encoding simple types in the JSON format.

Classes

See also
baljsn_encoder, baljsn_parserutil

Description

This component provides a struct of utility functions, baljsn::PrintUtil, for encoding a bdeat Simple type in the JSON format. The primary method is printValue, which encodes a specified object and is overloaded for all bdeat Simple types. The following table describes the format in which various Simple types are encoded.

Refer to the details of the JSON encoding format supported by this utility in the package documentation file (doc/baljsn.txt).

Usage

This section illustrates intended use of this component.

Example 1: Encoding a Simple struct into JSON

Suppose we want to serialize some data into JSON.

First, we define a struct, Employee, to contain the data:

struct Employee {
const char *d_firstName;
const char *d_lastName;
int d_age;
};

Then, we create an Employee object and populate it with data:

Employee john;
john.d_firstName = "John";
john.d_lastName = "Doe";
john.d_age = 20;

Now, we create an output stream and manually construct the JSON string using baljsn::PrintUtil:

oss << '{' << '\n';
oss << ':';
baljsn::PrintUtil::printValue(oss, john.d_firstName);
oss << ',' << '\n';
oss << ':';
baljsn::PrintUtil::printValue(oss, john.d_lastName);
oss << ',' << '\n';
oss << ':';
oss << '\n' << '}';
Definition bslstl_ostringstream.h:175
static int printValue(bsl::ostream &stream, bool value, const EncoderOptions *options=0)
Definition baljsn_printutil.h:410

Finally, we print out the JSON string:

if (verbose) {
bsl::cout << oss.str();
}
void str(const StringType &value)
Definition bslstl_ostringstream.h:581

The output should look like:

{
"firstName":"John",
"lastName":"Doe",
"age":20
}