JSON for Modern C++ 是一个由德国大牛 nlohmann 编写的在 C++ 下使用的 JSON 库。
下载地址传送门:json下载
实例代码
#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"]="ds";
js["to"]="cs";
js["msg"]="hello,go go go";
string sendBuf=js.dump();
cout<<sendBuf.c_str()<<endl;
}
//json序列化2
void func2()
{
json js;
//添加数组
js["id"]={1,2,3,4,5};
//添加对象
js["name"]="ds";
//添加对象
js["msg"]["ds"]="hello world";
js["msg"]["cn"]="hello china";
//等同于下面这句
js["msg"]={{"ds","hello world"},{"cn","hello china"}};
cout<<js<<endl;
}
//json实例化代码3
void func3()
{
json js;
//序列化一个vector容器
vector<int>vec;
vec.push_back(1);
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
js["list"]=vec;
//序列化一个map容器
map<int,string>m;
m.insert({1,"ds"});
m.insert({2,"cn"});
m.insert({3,"co"});
m.insert({4,"os"});
js["path"]=m;
string sendBuf=js.dump();//json数据对象 ->序列化 json字符串
cout<<sendBuf.c_str()<<endl;
}
int main()
{
func1();
func2();
func3();
return 0;
}