为什么Boost属性树write_json会将所有内容保存为字符串?有可能改变吗? [英] Why does Boost property tree write_json save everything as string? Is it possible to change that?
问题描述
我正在尝试使用boost属性树write_json进行序列化,它将所有内容保存为字符串,这并不是数据错误,但是我每次都需要显式转换它们,并且想在其他地方使用它们. (例如在python或其他C ++ json(非增强型)库中)
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();
和my_string_to_send_somewhere_else
是sth.像这样:
{
"path1" :
{
"path2" :
[
{
"key0" : "0",
"key1" : "true"
},
{
"key2" : "2.2",
"key3" : "3.3"
}
]
}
}
是否仍然可以将它们另存为值,例如:
"key1" : true
或"key2" : 2.2
?
Is there anyway to save them as the values, like:
"key1" : true
or "key2" : 2.2
?
推荐答案
我能想到的最简单,最干净的解决方案是使用占位符生成JSON,最后用实际值替换掉多余的引号.
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.
static string buildGetOrdersCommand() {
ptree root;
ptree element;
element.put<string>("pendingOnly", ":pendingOnly");
element.put<string>("someIntValue", ":someIntValue");
root.put("command", "getOrders");
root.put_child("arguments", element);
std::ostringstream buf;
write_json(buf, root, false);
buf << std::endl;
string json = buf.str();
replace(json, ":pendingOnly", "true");
replace(json, ":someIntValue", std::to_string(15));
return json;
}
static void replace(string& json, const string& placeholder, const string& value) {
boost::replace_all<string>(json, "\"" + placeholder + "\"", value);
}
结果是
{"command":"getOrders","arguments":{"pendingOnly":true,"someIntValue":15}}
{"command":"getOrders","arguments":{"pendingOnly":true,"someIntValue":15}}
这篇关于为什么Boost属性树write_json会将所有内容保存为字符串?有可能改变吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!