Question

I would like to serialize a hierarchical data structure in C++. The project I'm working on uses boost so I'm using boost::property_tree::ptree as my data node structure.

We have higher level structures like Person which contain instances of lower level structures like Job (each person has a job). Person and Job each implement a ptreeify method. The idea is to serialize the hierarchy by having each object call ptreeify on each other object it contains. The resulting sub objects' property trees are then inserted as nodes in the containing object's property tree. The problem is that I can't figure out how to actually do the insertion.

Following this SO post leads to a run time error. I lack the knowledge/experience needed to understand what's causing it. See code below.

I also found this very similar question but I do not understand the answer at all and I suspect the use of insert avoids complication found there.

Question: how do you insert a property tree as a node in another property tree?

Here is the actual code. The run time error occurs within Person::ptreeify.

#include <boost/property_tree/json_parser.hpp>
using boost::property_tree::ptree;
using namespace std;

struct Job{
    std::string title;
    int hoursPerWeek;
    ptree ptreeify(void); //return a ptree representing this Job
    };

ptree Job::ptreeify(){
    ptree pt;
    pt.put("title", title);
    pt.put("hours", hoursPerWeek);
    return pt;
    }

struct Person{
    std::string name;
    Job job;
    ptree ptreeify(void); //return a ptree representing this Person
                          //This must iterively call ptreeify on all sub-objects
    void save(const std::string &filename); //write this Person to file
    };

ptree Person::ptreeify(){
    ptree pt;
    pt.put("name", name);
    pt.put("job", "");

    ptree jobPt;
    jobPt = job.ptreeify();
    std::cout << "Program dies after this line" << std::endl;
    //This next line causes a run time error
    pt.insert(pt.get_child("job").begin(), jobPt.begin(), jobPt.end());
    return pt;
    }

void Person::save(const std::string &filename){
    ptree pt;
    pt = ptreeify();
    write_json(filename, pt);
    };

int main(){
    Person myPerson;
    myPerson.name = "Julius";

    Job myJob;
    myJob.title = "monkey";
    myJob.hoursPerWeek = 40;

    myPerson.job = myJob;

    myPerson.save("myPerson.dat");
    }
Était-ce utile?

La solution

It turns out this is really simple. You use put_child

ptree Person::ptreeify(){
    ptree pt;
    pt.put("name", name);

    ptree jobPt;
    jobPt = job.ptreeify();
    pt.put_child("job", jobPt);
    return pt;
    }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top