集群聊天服务器(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画等号。

相关推荐
RD_daoyi11 小时前
Google 官方调整抓取工具 IP 文件路径:SEO 与服务器安全策略要变了?
服务器·人工智能·学习·tcp/ip·搜索引擎·chatgpt
鬼才血脉11 小时前
IDEA中集成Tomcat后重新部署、重启服务器、更新资源、更新类和资源的使用
java·服务器·intellij-idea
zzzsde11 小时前
【Linux网络】传输层协议UDP
linux·服务器·开发语言·网络·算法·udp
格发许可优化管理系统11 小时前
解决Mentor许可冲突,让您的业务无缝运行
运维·服务器·c语言·c++·人工智能
上海云盾-小余11 小时前
服务器入侵应急处置:入侵排查与溯源恢复全流程
运维·服务器·github
Smile_25422041811 小时前
1panel - 网站结合php运行时环境 - openresty、php双容器如何挂载宿主机目录
运维·php
zt1985q11 小时前
本地部署开源向量数据库 Weaviate 并实现外部访问
运维·数据库·网络协议·开源
Mr.Daozhi11 小时前
用 WSL/Ubuntu 在本地部署开源大模型,彻底解决英文文献阅读难题
linux·运维·ubuntu
qq_白羊座11 小时前
CI/CD 与 DevOps 三
运维·ci/cd·devops