Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing and deserializing JSON with Boost

I'm newbie to C++. What's the easiest way to serialize and deserialize data of type std::Map using boost. I've found some examples with using PropertyTree but they are obscure for me.

like image 873
user1049280 Avatar asked Sep 12 '12 18:09

user1049280


People also ask

What is serializing and deserializing JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).

What is Boost serialization?

The library Boost. Serialization makes it possible to convert objects in a C++ program to a sequence of bytes that can be saved and loaded to restore the objects.

What is meant by serializing JSON?

JSON serialization JSON is an open standard that is commonly used for sharing data across the web. JSON serialization serializes the public properties of an object into a string, byte array, or stream that conforms to the RFC 8259 JSON specification.


2 Answers

Note that property_tree interprets the keys as paths, e.g. putting the pair "a.b"="z" will create an {"a":{"b":"z"}} JSON, not an {"a.b":"z"}. Otherwise, using property_tree is trivial. Here is a little example.

#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();
}
like image 114
5 revs, 4 users 77% Avatar answered Oct 03 '22 00:10

5 revs, 4 users 77%


Boost versions 1.75 and later now have a robust native JSON library:

https://www.boost.org/doc/libs/develop/libs/json/doc/html/index.html

I don't suggest using Boost.PropertyTree's JSON algorithms anymore, as they are not fully compliant with the spec.

like image 28
Vinnie Falco Avatar answered Oct 03 '22 00:10

Vinnie Falco