c ++如何将类序列化为json并解析json文件?

时间:2016-03-23 21:36:01

标签: c++ json parsing serialization deserialization

我有一个xObject类,它基本上是一个简单的“Person”类,我希望能够将整个类序列化为.json文件,然后读取该文件以便能够从中提取变量将这些变量归档并链接到类的名称。

例如:

xObject类代码:

class xObject{
    string name;
    string lastname;
    int age;

    public:
        string getName(){
            return name;
        }
        string getLastname(){
            return lastname;
        }
        int getAge(){
            return age;
        }
}

然后我创建了一个带有一些属性的对象。

int main(){

    xObject homer;
    homer.name = "Homer";
    homer.lastname = "Simpson";
    homer.age = 30;

    //SERIALIZATION OF HOMER.
    homer.serialExport("File.json")

    return 0;
}

所以现在,我的File.json应该是这样的:

{"homer" :
    {"name" : "Homer"
     "lastname" : "Simpson"
     "age" : 30
    }
}

然后,我希望能够从文件中读取以从中提取数据:

int main(){

    xObject bart;
    bart.name = "Bart";
    //ACTUAL USE OF THE .JSON FILE HERE
    myFile = ("File.json");
    bart.lastname = Deserializer(myFile).getLastname(); //It is supossed to assign "Simpson" 
                                                        //to the lastname reading from the serialized 
                                                        //homer class file described above.
    bart.age = Deserializer(myFile).getAge() - 20; //Sets homer's age minus 20 years.

    return 0;
}    

那么,我怎样才能在c ++上做到这一点? (图书馆实施已接受)

我怎样才能检索已经序列化的类名?

例如Deserialize(myFile).getClassName()应该返回"homer"

我在Java中使用XML序列化做了类似的事情,而且非常简单,但似乎在C ++中这不是很容易做到的,而且我对C ++相对较新。

1 个答案:

答案 0 :(得分:2)

在c ++中没有内省/反射,因此如果不在流中显式编写成员变量,则无法自动序列化类。出于同样的原因,您无法检索已序列化的类名。

所以解决方案是在你的类中编写一个函数来序列化你想要的成员变量。

当然你不会重新发明轮子来格式化json中的文件。您可以使用:https://github.com/open-source-parsers/jsoncpp

例如,你可以写:

Json::Value root;
root["homer"]["name"]="Homer";
root["homer"]["lastname"]="Simpson";
//etc

ofstream file;
file.open("File.json"); 
file << root;           
file.close();

但是,对于阅读,您可以按照自己的意愿进行操作:

Json::Value root2;
ifstream file2;
file2.open("File.json");
file2 >> root2;
file2.close();

xObject homer;
homer.lastname = root2["homer"]["lastname"].toStyledString();
//etc

当然,您的属性必须是公开的。否则你需要添加一个setter函数。