Search code examples
c++jsonboostboost-propertytree

Boost Json Write error: no matching function for call to ‘boost::property_tree::basic_ptree<std::__cxx11


I am trying to write Json data to a string using Boost library but I am facing a compilation error:

error: no matching function for call to ‘boost::property_tree::basic_ptree<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> >::push_back(std::pair<const char*, const char*>)

My c++ code is

#include <fstream>
#include <iostream>

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

namespace pt = boost::property_tree;

int main()
{
  std::string enc = "Enoded data";

    pt::ptree root;
    pt::write_json(std::cout, root);

    pt::ptree image_node;
    image_node.push_back(std::make_pair("content", enc));
    root.add_child("image", image_node);

    pt::ptree features_node;
    features_node.push_back(std::make_pair("type", "LABEL_DETECTION"));
    features_node.push_back(std::make_pair("maxResults", 1)); 
    root.add_child("features", features_node);
    pt::write_json(std::cout, root);
    return 0;
}

Solution

  • boost::property_tree::ptree::push_back takes a boost::property_tree::ptree::value_type as parameter, which is not the same as std::pair<const char*, const char*>. So, you'd need eg. :

    features_node.push_back(pt::ptree::value_type("type", pt::ptree("LABEL_DETECTION")));
    

    Or better yet, just use boost::property_tree::ptree::put :

    pt::ptree root;
    
    root.put("image.content", enc);
    root.put("features.type", "LABEL_DETECTION");
    root.put("features.maxResults", 1);
    
    pt::write_json(std::cout, root);