使用的是json三方库json for modern c++
先使用json定义一个对象,可以想象成STL容器,中间储存的一个个的键值对
#include <cstdio>
#include<iostream>
#include"json/json.h"
#include"json.hpp"
#include<vector>
#include<map>
using json = nlohmann::json;
using namespace std;
void func() {
json js; //定义一个json对象,类似于STL
js["msg_type"] = 2;
js["from"] = "zhang san";
js["to"] = "li si";
js["msg"] = "hello,what are you doing now";
cout << js << endl; //json类型的可以直接输出
string sendbuf = js.dump();
cout << sendbuf.c_str() << endl; //网络传输的时候转成char*类型
}
int main()
{
func();
cout << "hello,world" << endl;
return 0;
}
可以看到输出的结果形式上没有区别
json还有一个强大功能,可以序列化容器
void func() {
json js;
vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
js["list"] = vec;
map<int, string> map1;
map1.insert({ 1,"zhang san" });
map1.insert({ 2,"li si" });
map1.insert({ 3,"wang wu" });
js["map"] = map1;
cout << js << endl;
}
int main()
{
func();
cout << "hello,world" << endl;
return 0;
}
json的反序列化,将序列化的字符串反序列化为一个json的对象
string func2()
{
json js;
js["msg_type"] = 2;
js["from"] = "zhang san";
js["to"] = "li si";
js["msg"] = "hello,how are you";
string sendbuf = js.dump(); //序列化为json字符串
return sendbuf;
}
int main()
{
//json的反序列化,字符串反序列为json对象
json rec_buf = json::parse(func2());
cout << rec_buf << endl;
cout << "hello,world" << endl;
return 0;
}
json反序列化是能够将数据类型完全保存的
string func2()
{
json js;
js["arr"] = { 1,2,3,4,5 }; //数组
js["msg_type"] = 2; //int
js["name"] = "zhang san"; //字符串
js["country"]["city"] = "CQ"; //json
string sendbuf = js.dump(); //序列化为json字符串
return sendbuf;
}
int main()
{
//json的反序列化,字符串反序列为json对象
json rec_buf = json::parse(func2());
auto arr = rec_buf["arr"];
cout << arr[2] << endl;
cout << rec_buf["msg_type"] << endl;
json rec_js = rec_buf["country"];
cout << rec_js["city"] << endl;
return 0;
}
这个三方库非常轻量,也非常方便,很好用
JSON for Modern C++