使用Boost ptree解析std :: string

时间:2015-07-10 10:09:18

标签: c++ boost

我有这段代码

POST

我需要将JSON字符串解析为std::string ss = "{ \"item1\" : 123, \"item3\" : 456, \"item3\" : 789 }"; // Read json. ptree pt2; std::istringstream is(ss); read_json(is, pt2); std::string item1= pt2.get<std::string>("item1"); std::string item2= pt2.get<std::string>("item2"); std::string item3= pt2.get<std::string>("item3"); ,如上所示,我尝试在此处放置一个catch语句,但实际错误仅为std::string

所以我假设read_json只是读取文件而不是std :: string,以什么方式可以解析这个<unspecified file>(1):

1 个答案:

答案 0 :(得分:0)

您的样本从读取(如果您愿意,就像“文件”一样)。该字符串已用填充。所以你要解析你的字符串。你不能直接从字符串中解析。

然而,您可以使用Boost Iostreams直接从源字符串中读取而无需复制:

<强> Live On Coliru

#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>

namespace pt = boost::property_tree;

std::string ss = "{ \"item1\" : 123, \"item2\" : 456, \"item3\" : 789 }";

int main()
{
    // Read json.
    pt::ptree pt2;
    boost::iostreams::array_source as(&ss[0], ss.size());
    boost::iostreams::stream<boost::iostreams::array_source> is(as);

    pt::read_json(is, pt2);
    std::cout << "item1 = \"" << pt2.get<std::string>("item1") << "\"\n";
    std::cout << "item2 = \"" << pt2.get<std::string>("item2") << "\"\n";
    std::cout << "item3 = \"" << pt2.get<std::string>("item3") << "\"\n";
}

那只会少复制。它不会导致不同的错误报告。

考虑在字符串中包含换行符,以便解析器报告行号。

相关问题