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

相关推荐
眠りたいです2 分钟前
Docker:认识Docker镜像仓库并进行拉取推送
运维·nginx·docker·容器·busybox
西格电力科技8 分钟前
绿电直连架构适配技术的发展趋势
大数据·服务器·数据库·架构·能源
有味道的男人9 分钟前
1688数据采集:官方API与网页爬虫实战指南
java·服务器·爬虫
不想画图13 分钟前
Ansible自动化运维工具及基础用法
运维·自动化·ansible
爱尔兰极光18 分钟前
计算机网络--IPv4地址
服务器·网络·计算机网络
大猫和小黄19 分钟前
Ubuntu环境下GitBlit安装部署与版本库迁移
linux·运维·git·ubuntu·gitblit
sdyeswlw21 分钟前
一二三物联网医院后勤综合运维管理系统:让后勤保障更智能、更省心
运维·物联网
管理大亨37 分钟前
光伏大棚智慧管理:ELK数据中枢
大数据·运维·elk·elasticsearch
KingRumn37 分钟前
Linux进程间通信之消息队列(POSIX)实现篇
linux·服务器
未来之窗软件服务37 分钟前
幽冥大陆(五十四)ASR C语言识别到自动化软件——东方仙盟筑基期
运维·自动化·仙盟创梦ide·东方仙盟·东方仙盟自动化·东方仙盟商业开发