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 and I want to use them somewhere else. (like in python or other C++ json (non boost) library)
here is some sample code and what I get depending on locale:
boost::property_tree::ptree root, arr, elem1, elem2;
elem1.put<int>("key0", 0);
elem1.put<bool>("key1", true);
elem2.put<float>("key2", 2.2f);
elem2.put<double>("key3", 3.3);
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_somewhare_else = ss.str();
and my_string_to_send_somewhere_else
is sth. like this:
{
"path1" :
{
"path2" :
[
{
"key0" : "0",
"key1" : "true"
},
{
"key2" : "2.2",
"key3" : "3.3"
}
]
}
}
Is there anyway to save them as the values, like:
"key1" : true
or "key2" : 2.2
?
Boost confirms its implementation has no 100% conformance to JSON standard. Check the following link to see their explanation: Making a ptree variant that preserves JSON types is a future plan, but far off.!
As we have typedef basic_ptree<std::string, std::string> ptree; in the boost libraries, boost will always serialize each value as string and parse all values to a string equivalent.
The simplest and cleanest solution that i could come up with was generating the JSON with placeholders and in the end string replacing with the actual value ditching the extra quotes.
And the result is
From the outputted JSON it is clear that the serializer serializes everything to strings using some sort of .toString() method - that is, its unaware of the type of each member and so encloses everything in " ".
See Creating JSON arrays in Boost using Property Trees for more about this problem .
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
andjson_parser_write.hpp
to my project) and modified the following lines injson_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:
and simply saved string using:
complete program:
result :)