Files
cpp-httplib/docs-src/pages/ja/cookbook/c02-json.md
yhirose 0fa4912891 Fix broken relative links in cookbook docs (Fix #2490)
Cookbook body links referenced sibling pages with a bare slug
(e.g. `c14-keep-alive`). Under the pretty-URL layout each page lives
in its own directory, so these resolve against the page's own
directory and 404. Prefix them with `../` to match the convention
already used in the tour and llm-app sections.

Verified clean with `docs-gen check`.
2026-07-08 22:45:29 -04:00

1.6 KiB

title, order, status
title order status
C02. JSONを送受信する 2 draft

cpp-httplibにはJSONパーサーが含まれていません。JSONの組み立てや解析にはnlohmann/jsonなどのライブラリを使ってください。ここではnlohmann/jsonを例に説明します。

JSONを送信する

httplib::Client cli("http://localhost:8080");

nlohmann::json j = {{"name", "Alice"}, {"age", 30}};
auto res = cli.Post("/api/users", j.dump(), "application/json");

Post()の第2引数にJSON文字列、第3引数にContent-Typeを渡します。Put()Patch()でも同じ形です。

Warning: 第3引数のContent-Typeを省略すると、サーバー側でJSONとして認識されないことがあります。"application/json"を必ず指定しましょう。

JSONレスポンスを受け取る

auto res = cli.Get("/api/users/1");
if (res && res->status == 200) {
  auto j = nlohmann::json::parse(res->body);
  std::cout << j["name"] << std::endl;
}

res->bodystd::stringなので、そのままJSONライブラリに渡せます。

Note: サーバーがエラー時にHTMLを返すことがあります。ステータスコードを確認してからパースすると安全です。また、APIによってはAccept: application/jsonヘッダーが必要です。JSON APIを繰り返し呼ぶならC03. デフォルトヘッダーを設定するが便利です。

サーバー側でJSONを受け取って返す方法はS02. JSONリクエストを受け取りJSONレスポンスを返すを参照してください。