我正在使用boost ptree创建一个json字符串,这是我的代码:
int main()
{
ptree pt;
ptree commands;
pt.put<int>("mCommandID", 1);
pt.put<int>("mTimeSent", 0);
pt.add_child("commands", commands);
write_json(cout,pt);
}
但是此代码的输出是:
{
"mCommandID": "1",
"mTimeSent": "0",
"commands": ""
}
我喜欢它:
{
"mCommandID": "1",
"mTimeSent": "0",
"commands": "{}"
}
怎么可能?
答案 0 :(得分:2)
你想在JSON中使用JSON,所以你想要write_json两次:
<强> Live On Coliru 强>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <iostream>
using namespace boost::property_tree;
std::string to_json_string(ptree const& pt)
{
std::ostringstream oss;
json_parser::write_json(oss, pt, false);
return oss.str();
}
int main()
{
ptree pt;
ptree commands;
pt.put<int>("mCommandID", 1);
pt.put<int>("mTimeSent", 0);
pt.put("commands", to_json_string(ptree {}));
pt.put("more-commands", to_json_string(pt)); // a crude example
json_parser::write_json(std::cout, pt);
}
打印
{
"mCommandID": "1",
"mTimeSent": "0",
"commands": "{}\n",
"more-commands": "{\"mCommandID\":\"1\",\"mTimeSent\":\"0\",\"commands\":\"{}\\n\"}\n"
}