我有一个看起来像这样的json字符串:
[
"some text",
648547,
94.0,
111.0267520223,
10
]
所以我需要为每个值分配一个变量,如:
std::string value1 = "some text";
int value2 = 648547;
float value3 = 94.0;
float value4 = 111.0267520223;
int value5 = 10;
阅读JSON,使用Boost,我正在做这样的事情
std::stringstream jsonResponse;
boost::property_tree::ptree pt;
jsonResponse << "[\"some text\", 648547, 94.0, 111.0267520223, 10]";
std::istringstream is(jsonResponse);
boost::property_tree::read_json(is, pt);
但我不知道如何从属性树中读取数组值。
有没有人知道该怎么做?
提前感谢!
这里我的迭代没有命名数组的解决方案:
boost::property_tree::basic_ptree<std::string,std::string>::const_iterator iter = pt.begin(),iterEnd = pt.end();
for(;iter != iterEnd;++iter)
{
//->first; // Key. Array elements have no names
//->second; // The object at each step
std::cout << "=> " << iter->second.get_value<std::string>() << std::endl;
}
答案 0 :(得分:1)
您需要为数组命名,以便引用它:
{
"blah": [
"some text",
648547,
94.0,
111.0267520223,
10
]
}
这将在jsonlint.com上验证,但使用属性树读取仍然不容易。
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/exceptions.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <boost/foreach.hpp>
typedef boost::property_tree::iptree ptree_t;
typedef ptree_t::value_type ptree_value_t;
typedef boost::optional<ptree_t &> optional_ptree_t;
void parseMyJson()
{
optional_ptree_t ptBlah = pt.get_child_optional("blah");
if (ptBlah)
{
BOOST_FOREACH (property_tree_t::value_type & field, pt.get_child("blah"))
{
}
}
}
使用这种代码,您可以在blah中迭代字段,但由于它们是不同的类型,因此不能直接解析。
我建议您考虑命名字段,以便直接引用它们。
e.g。
field.second.get<string>("fieldname", "");
请记住将此代码包装在trycatch块中,因为boost属性树会在出现问题的第一个迹象时抛出异常(例如解析失败或找不到字段等)。
您可能会考虑使用更友好的json库(https://github.com/nlohmann/json)。