我在为项目使用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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句