I\'m trying to serialize using boost property tree write_json, it saves everything as strings, it\'s not that data are wrong, but I need to cast them explicitly every time a
Ok, I've solved it like this, (of course it won't suite for everybody, as it is a bit of a hack, that need further work).
I've wrote my own write_json
function (simply copied the files, json_parser.hpp
and json_parser_write.hpp
to my project) and modified the following lines in json_parser_write.hpp
:
stream << Ch('"') << data << Ch('"'); ==> stream << data;
Then values will be saved properly except for strings, so I wrote custom translator for it:
template
struct my_id_translator
{
typedef T internal_type;
typedef T external_type;
boost::optional get_value(const T &v) { return v.substr(1, v.size() - 2) ; }
boost::optional put_value(const T &v) { return '"' + v +'"'; }
};
and simply saved string using:
elem2.put("key2", "asdf", my_id_translator());
complete program:
#include
#include
#include
#include
#include "property_tree/json_parser.hpp" // copied the headers
template
struct my_id_translator
{
typedef T internal_type;
typedef T external_type;
boost::optional get_value(const T &v) { return v.substr(1, v.size() - 2) ; }
boost::optional put_value(const T &v) { return '"' + v +'"'; }
};
int main(int, char *[])
{
using namespace std;
using boost::property_tree::ptree;
using boost::property_tree::basic_ptree;
try
{
ptree root, arr,elem2;
basic_ptree elem1;
elem1.put("int", 10 );
elem1.put("bool", true);
elem2.put("double", 2.2);
elem2.put("string", "some string", my_id_translator());
arr.push_back( std::make_pair("", elem1) );
arr.push_back( std::make_pair("", elem2) );
root.put_child("path1.path2", arr);
std::stringstream ss;
write_json(ss, root);
std::string my_string_to_send_somewhere_else = ss.str();
cout << my_string_to_send_somewhere_else << endl;
}
catch (std::exception & e)
{
cout << e.what();
}
return 0;
}
result :)
{
"path1":
{
"path2":
[
{
"int": 10,
"bool": true
},
{
"double": 2.2,
"string": "some string"
}
]
}
}