JSON
Garvan reads JSON through crow::json::rvalue and writes it through crow::json::wvalue. There's also a thin wrapper JsonValue in the tools directory for use outside of request handlers.
Reading JSON
Parse an incoming request body and access fields by key:
CROW_ROUTE(app, "/api/echo")
.methods("POST"_method)
([](const crow::request &req) {
auto body = crow::json::load(req.body);
if (!body) return crow::response(400, "invalid json");
std::string name = body["name"].s();
int age = body["age"].i();
return crow::response("hello " + name);
});
load returns a falsy value when parsing fails, so always check before accessing fields.
Writing JSON
Build a wvalue and return it; Garvan sets Content-Type: application/json automatically.
CROW_ROUTE(app, "/api/user")([] {
crow::json::wvalue out;
out["id"] = 42;
out["name"] = "Ada";
out["roles"] = crow::json::wvalue::list({ "admin", "editor" });
return out;
});
Garvan JsonValue
JsonValue (alias json inside route headers) is a slim wrapper that adds a few conveniences for use inside services. The UserMysqlController in the bundled starter, for example, returns a JsonValue from its index() method.
#include "tools/JsonValue.h"
using json = JsonValue;
json users;
users.append({ {"id", 1}, {"name", "Ada"} });
users.append({ {"id", 2}, {"name", "Bo"} });
return users;