Chapter 12: JSON Parsing and Generation
An HTTP body is raw bytes, JsonCpp performs parsing, and JsonHelper provides a small set of convenience wrappers.
1. HTTP and JSON Boundaries
request.bodyView() returns a view of the body; it does not prove that the bytes are valid JSON. Validation covers Content-Type, body limits, parsing success, object shape, and field types.
2. Explicit parsing in a server handler
Json::CharReaderBuilder builder;
Json::Value input;
std::string errors;
// bodyView() is non-owning; parse it while the current request is alive.
const std::string_view body = request.bodyView();
std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
if(!reader->parse(body.data(), body.data() + body.size(), &input, &errors))
return client.sendText("invalid json", "400 Bad Request") ? -1 : -2;
if(!input.isMember("name") || !input["name"].isString())
return client.sendText("name is required", "422 Unprocessable Entity") ? -1 : -2;3. JsonHelper contracts
| API | Behavior | Failure or boundary |
|---|---|---|
toString(Value) | Compact JSON serialization | A JSON string value includes JSON quotes |
toJsonArray(text) | Parses into Json::Value | Prints an error and returns an empty value on failure; server code normally parses explicitly |
createJson(...) | Creates a flat object from key/value pairs | Arguments are passed as key/value pairs; booleans remain JSON booleans |
createArray(...) | Creates an array | Use Json::Value directly for complex nesting |
jsonAdd(a,b) | Merges objects or appends arrays | Returns an empty string on parse failure or mixed container types |
getValue() | Extracts a field or array element | -1 failure, 0 scalar, 1 object/array |
4. Field types and validation
const std::string text = stt::data::JsonHelper::createJson(
"ok", true,
"count", 3,
"message", "ready");
Json::Value value = stt::data::JsonHelper::toJsonArray(text);
if(value.isObject() && value["ok"].isBool())
std::cout << value["ok"].asBool() << '
';Manual JSON concatenation is prone to escaping, type, and structural errors. Escaping, Unicode, numbers, and booleans are easy to corrupt. Body-size limits, object structure, and field types form the validation boundary before field access.