-
序列化和反序列化通常用于在不同系统之间或者在不同平台上传输数据,例如在客户端和服务器之间的通信。
-
序列化是将数据结构或对象转换为可以在网络上传输或者存储的形式的过程
-
在序列化过程中,对象的状态被转换为字节流或者其他格式的数据,以便于传输或者存储。
-
反序列化是序列化的逆过程,即将序列化后的数据重新转换为对象或者数据结构的过程。
-
在反序列化过程中,从字节流或者其他格式的数据中恢复对象的状态。
-
Linux下使用Json库
- 安装Json库
sudo yum install jsoncpp-devel - 安装目录在
usr/include下 - 使用Json编译时加
-ljsoncpp选项
- 安装Json库
使用示例:
#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
struct Studnet
{
Studnet(std::string name, int age, int sex)
: _name(name), _age(age), _sex(sex)
{
}
std::string _name;
int _age;
int _sex;
};
int main()
{
Studnet s1("www", 18, 1);
// 序列化
Json::Value root;
root["name"] = s1._name;
root["age"] = s1._age;
root["sex"] = s1._sex;
Json::FastWriter write;
std::string str = write.write(root);
std::cout << str << std::endl;
// 反序列化
Json::Value root2;
Json::Reader read;
read.parse(str, root2);
s1._name = root2["name"].asCString();
s1._age = root2["age"].asInt();
s1._sex = root2["sex"].asInt();
std::cout << s1._name << s1._age << s1._sex << std::endl;
}