Quick Links:

bal | bbl | bdl | bsl

Namespaces

Component baljsn_printutil
[Package baljsn]

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

Namespaces

namespace  baljsn

Detailed Description

Outline
Purpose:
Provide a utility for encoding simple types in the JSON format.
Classes:
baljsn::PrintUtil utility for printing simple types in JSON
See also:
Component baljsn_encoder, Component 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:
  bsl::ostringstream oss;
  oss << '{' << '\n';
  baljsn::PrintUtil::printValue(oss, "firstName");
  oss << ':';
  baljsn::PrintUtil::printValue(oss, john.d_firstName);
  oss << ',' << '\n';
  baljsn::PrintUtil::printValue(oss, "lastName");
  oss << ':';
  baljsn::PrintUtil::printValue(oss, john.d_lastName);
  oss << ',' << '\n';
  baljsn::PrintUtil::printValue(oss, "age");
  oss << ':';
  baljsn::PrintUtil::printValue(oss, john.d_age);
  oss << '\n' << '}';
Finally, we print out the JSON string:
  if (verbose) {
      bsl::cout << oss.str();
  }
The output should look like:
  {
  "firstName":"John",
  "lastName":"Doe",
  "age":20
  }