定义:
网络通信:把应用层的结构化数据转化成一个“长字符串”存到网络中(序列化),再把“长字符串”中的内容解析形成结构化数据给对方(反序列化)
原因 :
(1)结构化的数据不利于网络传输,进行序列化和反序列化可以使应用层网络通信更加方便
(2)为了方便上层进行使用内部成员,将应用和网络解耦
使用Json:
命令
sudo yum install -y jsoncpp-devel
代码应用
#include <iostream>
#include <string>
#include <jsoncpp/json/json.h> //头文件
// 链接json库
// g++ -o test test_json.cc -ljsoncpp
typedef struct request
{
int x;
int y;
char op;
} request_t;
int main()
{
request_t req = {10, 20, '*'}; //*的ascii是42
// json是一种kv式的序列化方案
Json::Value root; //可以盛装任何对象
root["datax"] = req.x;
root["datay"] = req.y;
root["operator"] = req.op;
// FastWriter/StyledWriter 两种
// {
// "datax" : 10,
// "datay" : 20,
// "operator" : 42
// }
// Json::StyledWriter writer;
//{"datax":10,"datay":20,"operator":42}
Json::FastWriter writer;
std::string json_str = writer.write(root);
std::cout << json_str << std::endl;
// R:“”里的看成原生字符串,可以不转义 -std=c++11
std::string json_string = R"({"datax":10,"datay":20,"operator":42})";
Json::Reader reader;
Json::Value root2;
// 参数:反序列化的字符串;json value中间对象
reader.parse(json_string,root2);
request_t req2;
req2.x = root2["datax"].asInt();
req2.y = root2["datay"].asInt();
req2.op = (char)root2["operator"].asInt();
std::cout<<req2.x<<req2.op<<req2.y<<std::endl;
return 0;
}
运行结果
原始数据:10*20
序列化结果:{“datax”:10,“datay”:20,“operator”:42}
反序列化结果:10*20