我在为项目使用Boost属性树时遇到问题。我正在这样使用它:
using Namespace boost::property_tree;
ptree proot;
int myInt = 5;
proot.put("Number", myInt);
write_json("myjson.json", proot);
如果我这样使用它,则安全的数据类型是字符串,而不是int。我的意思是一个例子:{ "Number": "5" } //what i get
{ "Number": 5 } //what i want
有办法改变吗? 最佳答案
不,您不能更改此行为,因为字符串值类型已被烘焙到boost::property_tree
中。从技术上讲,您可以使用与默认模板类型不同的模板类型参数,但是您会松散进入该库的大部分转换逻辑。
作为一种有点怪异的选择,请考虑以下内容。
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
using namespace boost::property_tree;
using boost::property_tree::json_parser::create_escapes;
void writeJsonValue(std::ostream& stream, const ptree& pt)
{
const auto raw = pt.get_value<std::string>();
if (raw == "true" || raw == "false") {
stream << raw;
return;
}
if (const auto integral = pt.get_value_optional<int>())
stream << *integral;
else
stream << '"' << create_escapes(raw) << '"';
}
这从本质上还原了一些类型信息的预定义丢失。您可以在Boost的json输出功能的修改版本中使用此功能:void writeJson(std::ostream& stream, const ptree& pt, int indent = 0)
{
static const auto indentStr = [](int level) { return std::string(4 * level, ' '); };
if (indent > 0 && pt.empty())
writeJsonValue(stream, pt);
else if (indent > 0 && pt.count(std::string()) == pt.size()) {
stream << "[\n";
for (auto it = pt.begin(); it != pt.end(); ++it) {
stream << indentStr(indent + 1);
writeJson(stream, it->second, indent + 1);
if (boost::next(it) != pt.end())
stream << ',';
stream << '\n';
}
stream << indentStr(indent) << ']';
} else {
stream << "{\n";
for (auto it = pt.begin(); it != pt.end(); ++it) {
stream << indentStr(indent + 1);
stream << '"' << create_escapes(it->first) << "\": ";
writeJson(stream, it->second, indent + 1);
if (boost::next(it) != pt.end())
stream << ',';
stream << '\n';
}
stream << indentStr(indent) << '}';
}
}
调用它作为您的数据,例如如 writeJson(std::cout, proot);
并且输出应该是{
"Number": 5
}
关于c++ - 如何确定Boost属性树使用的数据类型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/64044195/