如何使用rapidjson反向解析?

时间:2015-06-25 07:43:14

标签: json rapidjson

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

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并将age更改为30,调用reverseParse()应返回:

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

如何写reverseParse()?

1 个答案:

答案 0 :(得分:0)

有一个rapidjson教程here

您的x=3 [3] SENDING 0 [3] SENDING 1 [3] SENDING 2 [3] fork1 successful [3] RECEIVING 3 [3] fork2 successful [3] fork1 successful [3] child1 pid=8267 [3] child2 pid=8268 [3] child1 exiting [3] process ID 8267 returned status 0. [3] Child1 ran. Child2 killed. x=2 [2] SENDING 0 [2] SENDING 1 [2] SENDING 2 [2] fork1 successful [2] RECEIVING 3 [2] fork2 successful [2] process ID 8268 returned status 9.This is NOT an exit status, so I will keep looping.... [2] fork1 successful [2] child1 pid=8270 [2] child2 pid=8271 [2] child1 exiting [2] process ID 8270 returned status 0. [2] Child1 ran. Child2 killed. x=1 [1] SENDING 0 [1] SENDING 1 [1] SENDING 2 [1] fork1 successful [1] RECEIVING 3 [1] fork1 successful [1] child1 pid=8273 [1] fork2 successful [1] process ID 8271 returned status 9.This is NOT an exit status, so I will keep looping.... [1] child2 pid=8274 [1] child1 exiting [1] process ID 8273 returned status 0. [1] Child1 ran. Child2 killed. 可能如下所示:

reverseParse()