LoginSignup
0
0

More than 1 year has passed since last update.

nlohmann json でバイナリを受け渡しする場合は、bson を使えば良い

Last updated at Posted at 2023-04-10

バイナリデータを受け渡しする C++ プログラムが必要だったので nlohmann json の bson を使いました。
尚、bson なら C# や Java でも読み書きができます。(cbor もあるけどまた今度)
これは、コードの書きぶりのメモです。

main.cpp
#include <iostream>

#include <nlohmann/json.hpp>
using json = nlohmann::json;

int main(int argc, char *argv[])
{
    // (1)バイナリデータ書き込み
    std::string abc = "abc";
    std::vector<std::uint8_t> vec = std::vector<uint8_t>(abc.begin(), abc.end());
    json j;
    j["bin"] = json::binary(vec, 0);
    std::cout << j.dump(2) << std::endl;
    std::vector<std::uint8_t> bson = json::to_bson(j);

    // 通常は、ここで bson(バイト列)をファイルに書き込み、相手に転送して読み込む処理が入る
    std::vector<std::uint8_t> bson2 = std::vector<std::uint8_t>(bson.begin(), bson.end());

    // (2)バイナリデータ読み込み
    // j2 に読み込む
    json j2 = json::from_bson(bson2);
    std::cout << j2.dump(2) << std::endl;
    json::binary_t bin = j2["bin"].get_binary();
    std::vector<std::uint8_t> vec2 = std::vector<uint8_t>(bin.begin(), bin.end());
    std::string s = std::string(vec2.begin(), vec2.end());
    // std::string s = std::string(bin.begin(), bin.end()); // std::vector<std::uint8_t>型の変数が要らなければこれでもいける
    std::cout << s << std::endl;

    return 0;
}
実行結果
{
  "bin": {
    "bytes": [97, 98, 99],
    "subtype": 0
  }
}
{
  "bin": {
    "bytes": [97, 98, 99],
    "subtype": 0
  }
}
abc
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0