programing

Boost로 JSON 직렬화 및 역 직렬화

nasanasas 2020. 11. 21. 11:19
반응형

Boost로 JSON 직렬화 및 역 직렬화


저는 C ++의 초보자입니다. 무엇 직렬화하는 가장 쉬운 방법 및 유형의 직렬화 데이터의 std::Map사용 boost. 나는 사용과 관련된 몇 가지 예를 찾았 PropertyTree지만 저에게는 모호합니다.


참고 것을 property_treeJSON 아닌 { "AB": "Z"} 예 경로로서 해석 키 쌍 "AB"를 가하고 = "Z"는 {{ "B", "Z"} "A"를} 만드는 것 . 그렇지 않으면 사용 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();
}

참고 URL : https://stackoverflow.com/questions/12394472/serializing-and-deserializing-json-with-boost

반응형