假设我从网络接收到JSON格式化字符串,并希望在Boost属性树中对其进行解码。最好的方法是什么?
答案 0 :(得分:1)
为了创建一个简单的例子,我们假设我们在代码中有一个字符串来表示您将从网络接收的字符串,其中包含以下内容:
{
"Test": "string",
"Test2":
{
"inner0": "string2",
"inner1": "string3",
"inner2": "1234"
}
}
因此,将其解释为字符串的代码如下:
#include <boost/property_tree/json_parser.hpp>
#include <iostream>
#include <sstream>
int main()
{
std::stringstream buffer("{ \"Test\": \"string\", \"Test2\": { \"inner0\": \"string2\", \"inner1\": \"string3\", \"inner2\": \"1234\" } }");
std::cout << buffer.str() << std::endl;
boost::property_tree::ptree pt;
boost::property_tree::json_parser::read_json(buffer, pt);
std::string test2_inner0_str = pt.get<std::string>("Test2.inner0");
int test2_inner2_value = pt.get<int>("Test2.inner2");
std::cout << test2_inner0_str << std::endl;
std::cout << test2_inner2_value << std::endl;
}
打印:
<强> Live On Coliru 强>
{ "Test": "string", "Test2": { "inner0": "string2", "inner1": "string3", "inner2": "1234" } }
string2
1234