与提升属性树JSON解析 [英] Parsing JSON with boost property tree
问题描述
我建设,从themoviedb.com获取电影信息的应用程序。这些信息是在一个JSON文件中提供。我试图用存储提升属性树的信息。但是有一个小问题。
I'm building an application that gets movie information from themoviedb.com. The information is provided in a JSON file. I'm trying to store the information using boost property tree. But There is a little problem.
我通过以下code说明问题:
I illustrate the problem by the following code:
#include <vector>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
using namespace std;
using boost::property_tree::ptree;
class single_t{
int sID;
string sName;
public:
void setID(int ID){sID=ID;}
int getID(){return sID;}
void setName(string Name){sName=Name;}
string getName(){return sName;}
};
typedef vector<single_t*> multiple_t;
class foo{
string fTitle;
multiple_t fItems;
public:
string getTitle(){return fTitle;}
void setTitle(string Title){fTitle=Title;}
multiple_t getItems(){return fItems;}
void setItems(multiple_t Items){fItems = Items;}
void setItems(single_t Item){fItems.push_back(&Item);}
};
int main () {
try{
string response = "{\"title\":\"Foo\",\"items\":[{\"id\":123,\"name\":\"test1\"},{\"id\":456,\"name\":\"test2\"}]}";
ptree pt;
stringstream ss; ss << response;
read_json(ss, pt);
foo results;
results.setTitle(pt.get<string>("title"));
BOOST_FOREACH(ptree::value_type &v,pt.get_child("items")){
single_t result;
result.setID(v.second.get<int>("id"));
result.setName(v.second.get<string>("name"));
results.setItems(result);
}
cout << "Tilte: " << results.getTitle() << endl;
cout << "Items:" << endl;
for (int i=0; i!=results.getItems().size(); i++) {
cout << "\tID: " << results.getItems()[i]->getID()<< endl;
cout << "\tName: " << results.getItems()[i]->getName()<< endl;
}
}
catch (exception& e)
{
cout << "Exception: " << e.what();
}
}
但是,当我运行此我得到以下的输出:
But when I run this I get the following output:
Tilte: Foo
Items:
ID: 456
Name: test2
ID: 456
Name: test2
有谁知道我做错了吗?我想这是在BOOST_FOREACH code。
Does anyone know what I'm doing wrong? I guess it is in the BOOST_FOREACH code.
PS:利用X code 4.5.2与LLVM GCC 4.2编译
PS: Using Xcode 4.5.2 with LLVM GCC 4.2 Compiler.
推荐答案
的问题是不是与 property_tree
,问题是,你试图存储指针到矢量局部变量。您可以通过保存的价值,或者使用一些智能指针(如的boost :: shared_ptr的
)。
Problem is not with property_tree
, problem is, that you try store pointer to local variable in vector. You can save by value, or use some smart pointer (for example boost::shared_ptr
).
问题:
void setItems(single_t Item){fItems.push_back(&Item);}
退出此功能后,局部变量项目
将被破坏,所以你必须悬挂指针。
After exit from this function, local variable Item
will be destroyed, so you have dangling pointer.
这篇关于与提升属性树JSON解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!