json序列化
json和xml有一样的功能,但是更简洁
json要么是键值对的集合({“key”:“vlaue”,”key2”:”value2”}),要么是一个列表/数组([value1,value2])
json支持的数据类型有
- object(例如键值对的集合,以左右花括号为限定符)
- array(例如列表和数组,以左右方括号为限定符)
- string
- number
- ”true”
- ”flase”
- ”null”
object的键(key)必须是string,值(value)可以是上述其中类型之一,这样就可以构建树形结构了
1 2 3 4 5 6
| [{"head":{ "mouth":{ "toot":32}, "eye":2, "nose":1}}, "body"]
|
序列化:复杂的数据结果通过json转换为字符串
json的使用
nlohmann/json 是一个header-only库,也就是写代码的时候只需要include一下头文件即可使用,不需要加链接选项
安装步骤:
- 先解压
- 找到singe_include下的nlohmann下的json_fwd.hpp和json.hpp
- 将这两个文件拷贝到当前工作目录
使用 构造object:
1 2 3 4 5 6 7 8 9 10 11 12 13
| #include "json.hpp" #include <iostream> using namespace std;
int main(){ nlohmann::json json_object; json_objec["key1"] = "value1"; json_object["key2"] = 1234; json_object["key3"]["key4"] = 12345; cout << json_object.dump()<<'\n'; }
|
使用 构造array:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| #include "json.hpp" #include <iostream> using namespace std; int main(){ nlohmann::json json_object; json_object.push_back("hello"); json_object[1] = "world"; json_object[2]["key1"] = "value" cout << json_object.dump(); cout << json_object[0] << 'n'; }
|
反序列化
1 2 3 4 5 6 7 8 9 10 11
| #include "json.hpp" #include <iostream> using namespace std;
int main(){ char arrp[] = {\"hello\","\world"\,{\"key4\":12345}}; nlohmann::json json_object = nlohman::json::parse(arr); cout << '[0]' << json_object[0] cout << '[2][key4]'<<jon_object[2]["key4"]; }
|