Files
cpp-httplib/docs-src/pages/ja/cookbook/c02-json.md
yhirose c95d799180 Polish the wording of the updated docs pages
Reword the Japanese sentences so they read naturally, and correct the
size of the llama.cpp server sources in the code reading chapter.
2026-10-08 20:39:13 -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が"application/json"でないと、サーバー側で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->bodyはstd::stringなので、そのままJSONライブラリに渡せます。

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

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