How to reverse parse using rapidjson?

475 views Asked by At

for example, I have a class to parse from string to object:

Student.h

class Student{
public:
    inline std::string getName(){
        return this->name;
    }

    inline void setName(std::string name){
        this->name=name;
    }

    inline int getAge(){
        return this->age;
    }

    inline void setAge(int age){
        this->age=age;
    }

    void parse(rapidjson::Value& value);

    //std::string reverseParse();
protected:
    std::string name
    int age;
};

Student.cpp

void Student::parse(rapidjson::Value& value){
    if(value["name"].IsString()){
        this->name=value["name"].GetString();
    }
    if(value["age"].IsInt()){
        this->age=value["age"].GetInt();
    }
}

//std::string Student::reverseParse(){
//}

main.cpp

int main(){
    rapidjson::Document doc;
    doc.Parse<0>("{\"name\":\"abc\",\"age\":20}").HasParseError();

    Student student;
    student.parse(doc);
    printf("%s %d\n",student.getName().c_str(),stundent.getAge());

    student.setName("def");
    student.setAge(30);
    //printf("%s\n",student.reverseParse().c_str());
    return 0;
}

which call parse(doc) to fill the value from json string, and the output should be:

abc 20

,now I want to reverse the parse process, convert the object to json string, by changing the name to def and changing the age to 30,calling reverseParse() should return:

{"name":"def","age":30}

how to write reverseParse()?

1

There are 1 answers

0
doqtor On BEST ANSWER

There is a rapidjson tutorial here.

Your reverseParse() could look like this:

std::string reverseParse()
{
    rapidjson::Document doc;
    doc.SetObject();
    rapidjson::Document::AllocatorType& allocator = doc.GetAllocator();

    doc.AddMember("name", this->name.c_str(), doc.GetAllocator());
    doc.AddMember("age", this->age, doc.GetAllocator());

    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
    doc.Accept(writer);

    return buffer.GetString();
}