我有这个代码
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");
Run Code Online (Sandbox Code Playgroud)
我需要将 JSON 字符串解析为std::string' ,如上所示,我尝试在此处放置一个 catch 语句,但实际的错误只是<unspecified file>(1):
所以我假设 read_json 只是读取文件,而不是 std::string,std::string可以以什么方式解析它?
您的示例从流中读取(如果您愿意的话,“就像一个文件”)。流已经被你的字符串填满了。所以你正在解析你的字符串。您不能直接从字符串中解析。
不过,您可以使用 Boost Iostreams 直接从源字符串读取,无需复制:
#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";
}
Run Code Online (Sandbox Code Playgroud)
这样只会减少复制量。不会导致不同的错误报告。
考虑在字符串中包含换行符,以便解析器报告行号。
| 归档时间: |
|
| 查看次数: |
3464 次 |
| 最近记录: |