简体   繁体   English

提升read_json和write_json对于属性树不是等价的

[英]Boost read_json and write_json are not equipollent for property tree

If I create a property tree from a stringstream with read_json, and I write it back to the stream with write_json, tryng to load it again with read_json fails with "terminate called after throwing an instance of 'boost::exception_detail::clone_impl >' what(): (1): expected object or array" 如果我使用read_json从字符串流创建属性树,然后使用write_json将其写回到流中,则尝试通过read_json再次加载它的过程将失败,并抛出“终止,并抛出'boost :: exception_detail :: clone_impl>实例” what():(1):预期对象或数组”

This code fails with the forementioned exception: 此代码因上述异常而失败:

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
using boost::property_tree::ptree;
ptree pt;
stringstream pippo("{\"size\":1000,\"reserved\":100,\"list\": {\"122\":1,\"123\":3}}");
read_json(pippo,pt);
write_json(pippo,pt,false);
read_json(pippo,pt);

BUT if I change my code this way, it works: 但是,如果我以这种方式更改代码,它会起作用:

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
using boost::property_tree::ptree;
ptree pt;
stringstream pippo("{\"size\":1000,\"reserved\":100,\"list\": {\"122\":1,\"123\":3}}");
read_json(pippo,pt);
write_json(pippo,pt,false);
stringstream pluto(pippo.str());
read_json(pluto,pt);

I write down the answer just in case someone makes the same mistake I did. 我写下答案,以防万一有人犯同样的错误。

read_json is designed for file, not string stream access, so when I feed it a stringstream written by from write_json, the stream was simply at eof. read_json是为文件而不是字符串流访问而设计的,因此当我向它提供由write_json编写的字符串流时,该流只是位于eof处。 This code now works: 该代码现在可以工作:

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
using boost::property_tree::ptree;
ptree pt;
stringstream pippo("{\"size\":1000,\"reserved\":100,\"list\": {\"122\":1,\"123\":3}}");
read_json(pippo,pt);
write_json(pippo,pt,false);
pippo.seekg(0,pippo.beg);
read_json(pippo,pt);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM