集群聊天服务器(2)Json介绍

目录

大家之间交流用json,想要发送数据,就把数据序列化成json,想要接收数据,就反序列化成自己程序的语言。

Json序列化

可以直接赋值一个容器对象

js['xx']=vec;

cpp 复制代码
#include "json.hpp"
using json=nlohmann::json;
#include <iostream>
#include <vector>
#include <map>
using namespace std;

//json序列化示例1
void func1(){
    json js;
    js["msg_type"]=2;
    js["from"]="zhang san";
    js["to"]="li si";
    js["msg"]="hello,what are you doing now?";

    cout<<js<<endl;
}

int main(){
    func1();

    return 0;
}

转成字符串,就可以通过网络发送

cpp 复制代码
#include "json.hpp"
using json=nlohmann::json;
#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;


//json序列化示例1
void func1(){
    json js;
    js["msg_type"]=2;
    js["from"]="zhang san";
    js["to"]="li si";
    js["msg"]="hello,what are you doing now?";

    string sendBuf=js.dump();
    cout<<sendBuf.c_str()<<endl;
}

int main(){
    func1();

    return 0;
}

还可以放数组,json形式还可以像是二维数组一样,键值对里面套键值对

cpp 复制代码
#include "json.hpp"
using json=nlohmann::json;
#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;


//json序列化示例1
void func1(){
    json js;
    js["id"]={1,2,3,4,5};
    js["msg_type"]=2;
    js["from"]="zhang san";
    js["to"]="li si";
    js["msg"]["zhang san"]="hello world";
    js["msg"]["liu shuo"]="hello china";


    cout<<js<<endl;
}

int main(){
    func1();

    return 0;
}

Json反序列化

cpp 复制代码
#include "json.hpp"
using json=nlohmann::json;
#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;


//json序列化示例1
void func1(){
    json js;
    js["id"]={1,2,3,4,5};
    js["msg_type"]=2;
    js["from"]="zhang san";
    js["to"]="li si";
    js["msg"]["zhang san"]="hello world";
    js["msg"]["liu shuo"]="hello china";


    cout<<js<<endl;
}

string func2(){
    json js;
    js["id"]={1,2,3,4,5};
    js["msg_type"]=2;
    js["from"]="zhang san";
    js["to"]="li si";
    js["msg"]["zhang san"]="hello world";
    js["msg"]["liu shuo"]="hello china";
    string sendBuf=js.dump();
    return sendBuf;

}

int main(){
    string recvBuf=func2();
    //数据的反序列化
    json jsbuf=json::parse(recvBuf);//返回一个json对象
    cout<<jsbuf["msg_type"]<<endl;
    cout<<jsbuf["from"]<<endl;
    cout<<jsbuf["to"]<<endl;
    cout<<jsbuf["msg"]<<endl;

    return 0;
}

json.hpp非常轻量,比任何第三方库都好用。做json的序列化和反序列化,能够直接将stl容器和json画等号。

相关推荐
腊笔不小新xingo3 小时前
Nginx 报错:413 Request Entity Too Large
运维·nginx
沧浪之水!3 小时前
Linux:Shell环境变量与命令行参数
linux·运维·服务器
勿幕3 小时前
【Jenkins】显示 HTML 标签
运维·jenkins
Hurry64 小时前
HAProxy的ACL
运维·服务器·网络
Jiaberrr4 小时前
Vue 3 + Vite 项目配置访问地址到服务器某个文件夹的解决方案
服务器·javascript·vue.js·部署·服务器配置
leafseelight5 小时前
在CentOS 7上添加Swap交换空间完整指南
linux·运维·centos
van_peak5 小时前
Centos 9 Could not resolve host: mirrors.centos.org问题
linux·运维·centos
网硕互联的小客服5 小时前
服务器为什么会禁止 Ping?服务器禁止 Ping 的好处
运维·服务器
福旺旺5 小时前
Linux实操——在服务器上直接从百度网盘下载(/上传)文件
linux·服务器
IU宝6 小时前
Linux的部分常用基础指令
linux·服务器