如何使用 rapidjson 进行反向解析?

How to reverse parse using rapidjson?

例如,我有一个 class 从字符串解析为对象:

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;
}

调用 parse(doc) 来填充 json 字符串的值,输出应该是:

abc 20

,现在我想反转解析过程,将对象转换为 json 字符串,通过将名称更改为 def 并将年龄更改为 30,调用 reverseParse() 应该 return:

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

reverseParse()怎么写?

有rapidjson教程here

您的 reverseParse() 可能如下所示:

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();
}