前言
Json是一种轻量级的数据交换格式(也叫数据序列化方式)。Json采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 Json 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
Json的特点
- 直观的语法
- 整个代码由一个头文件组成 json.hpp,没有子项目,没有依赖关系,没有复杂的构建系统,使用起来非常方便
- 使用 C++ 11 标准编写
- 使用 json 像使用 STL 容器一样
- STL 和 json 容器之间可以相互转换
- 严谨的测试:所有类都经过严格的单元测试,覆盖了 100% 的代码,包括所有特殊的行为。此
外,还检查了 Valgrind 是否有内存泄漏。为了保持高质量,该项目遵循核心基础设施倡议(CII)的最佳实践。
在网络中,常用的数据传输序列化格式有XML,Json,ProtoBuf,在公司级别的项目中,大量的在使用ProtoBuf作为数据序列化的方式,以其数据压缩编码传输,占用带宽小,同样的数据信息,是Json的1/10,XML的1/20,但是使用起来比Json稍复杂一些,所以项目中我们选择常用的Json格式来打包传输数据。
使用方法:
#include "json.hpp"
using json = nlohmann::json;
Json序列化示例
示例1
// 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;
}
示例2:转成字符串
// 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;
}
示例3:json的键值对不仅可以放普通的字符串,还可以添加数组,对象等复杂类型。
void func2() {
json js;
// 添加数组
js["id"] = {1, 2, 3, 4, 5};
// 添加key-value
js["name"] = "zhang san";
// 添加对象
js["msg"]["zhang san"] = "hello world";
js["msg"]["liu shuo"] = "hello China";
// 上面等同于下面这句一次性添加数组对象
js["msg"] = {{"zhang san", "hello world"}, {"liu shuo", "hello China"}};
cout << js << endl;
}
示例4:序列化STL的容器
void func3() {
json js;
vector<int> vec;
for (int i = 0; i < 5; ++i) {
vec.emplace_back(i + 1);
}
js["vector"] = vec;
map<int, string> m;
m.insert({1, "first"});
m.insert({2, "second"});
m.insert({3, "third"});
js["map"] = m;
cout << js << endl;
}
Json的反序列化示例
当从网络接收到字符串为Json格式,可以用JSON for Modern C++ 直接反序列化取得数据或者直接反序列化出对象,甚至容器,强大无比!
示例1:
// json序列化示例1
string 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;
return sendBuf;
}
int main(void) {
string recvBuf = func1();
json recvjs = json::parse(recvBuf);
cout << recvjs["msg_type"] << endl;
cout << recvjs["from"] << endl;
cout << recvjs["to"] << endl;
cout << recvjs["msg"] << endl;
return 0;
}
示例2:
string func2() {
json js;
// 添加数组
js["id"] = {1, 2, 3, 4, 5};
// 添加key-value
js["name"] = "zhang san";
// 添加对象
js["msg"]["zhang san"] = "hello world";
js["msg"]["liu shuo"] = "hello China";
// 上面等同于下面这句一次性添加数组对象
js["msg"] = {{"zhang san", "hello world"}, {"liu shuo", "hello China"}};
string sendBuf = js.dump();
cout << sendBuf.c_str() << endl;
return sendBuf;
}
int main(void) {
string recvBuf = func2();
json recvjs = json::parse(recvBuf);
cout << recvjs["id"] << endl;
auto nums = recvjs["id"];
cout << nums[2] << endl;
auto msgjs = recvjs["msg"];
cout << msgjs["zhang san"] << endl;
cout << msgjs["liu shuo"] << endl;
return 0;
}