web-dev-qa-db-ja.com

Boostを使用したJSONのシリアル化と逆シリアル化

私はC++の初心者です。 boostを使用してstd::Map型のデータをシリアル化および逆シリアル化する最も簡単な方法は何ですか。 PropertyTreeを使用したいくつかの例を見つけましたが、それらは私にはわかりません。

64
user1049280

property_treeはキーをパスとして解釈することに注意してください。ペア「a.b」= "z"を入れると、{"a.b": "z"}ではなく、{"a":{"b": "z"}} JSONが作成されます。それ以外の場合、property_treeの使用は簡単です。ここに小さな例があります。

#include <sstream>
#include <map>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

using boost::property_tree::ptree;
using boost::property_tree::read_json;
using boost::property_tree::write_json;

void example() {
  // Write json.
  ptree pt;
  pt.put ("foo", "bar");
  std::ostringstream buf; 
  write_json (buf, pt, false);
  std::string json = buf.str(); // {"foo":"bar"}

  // Read json.
  ptree pt2;
  std::istringstream is (json);
  read_json (is, pt2);
  std::string foo = pt2.get<std::string> ("foo");
}

std::string map2json (const std::map<std::string, std::string>& map) {
  ptree pt; 
  for (auto& entry: map) 
      pt.put (entry.first, entry.second);
  std::ostringstream buf; 
  write_json (buf, pt, false); 
  return buf.str();
}
90
ArtemGr