1.Json库的使用,包含C++ Json的创建、读写、字符串Json互转等,覆盖日常使用场景
-
前提:按照参考的文章部署好nlohmann/json
- 上代码
#include <iostream>
#include <fstream>
#include "nlohmann/json.hpp"
using json = nlohmann::json;
using namespace std;void CreateVoidJson(json& j)
{j["pi"] = 3.141;j["happy"] = true;j["name"] = "Niels";j["nothing"] = nullptr;j["answer"]["everything"] = 42; // 初始化answer对象j["list"] = { 1, 0, 2 }; // 使用列表初始化的方法对"list"数组初始化j["object"] = { {"currency", "USD"}, {"value", 42.99} }; // 初始化object对象cout << "------------------------------- 创建Json END -------------------------------------------\n" << endl;
}void PrintJsonInfo(json& j)
{float pi = j.at("pi");string name = j.at("name");int everything = j.at("answer").at("everything");cout << pi << endl; // 输出: 3.141cout << name << endl; // 输出: Nielscout << everything << endl; // 输出: 42// 打印"list"数组for (int i = 0; i < 3; i++)cout << j.at("list").at(i) << endl;// 打印"object"对象中的元素cout << j.at("object").at("currency") << endl; // 输出: USDcout << j.at("object").at("value") << endl; // 输出: 42.99cout << "------------------------------- 输出Json信息END -------------------------------------------\n" << endl;
}void OutputJson(json& j)
{ofstream file("Out.json");file << j << endl;cout << "\n------------------------------- 导出Json END -------------------------------------------\n" << endl;
}void JsonSwtichCString(json& j)
{//重载写法,返回一个Json对象j = "{\"happy\":true,\"pi\":3.141}"_json;auto j2 = R"({"happy":true,"pi":3.141})"_json;//或者string s = "{\"happy\":true,\"pi\":3.141}";auto j1 = json::parse(s.c_str());cout << j1.at("pi") << endl; // 输出:3.141//dump()返回 JSON 对象中存储的原始 string 值。s = j1.dump();cout << "dump()返回 JSON 对象中存储的原始 string 值:" << s << endl;cout << "------------------------------- Json字符串互转 END -------------------------------------------\n" << endl;
}void ReadJsonFile()
{ifstream i("Out.json");json j;i >> j;// 以易于查看的方式将json对象写入到本地文件ofstream o("Out1.json");o << std::setw(4) << j << endl;cout << "------------------------------- 读入Json END -------------------------------------------\n" << endl;
}void JsonSwapType()
{// 首先定义一个结构体struct person{std::string name;std::string address;int age;};person p = { "Ned Flanders", "744 Evergreen Terrace", 60 }; // 定义初始化p// 从结构体转换到json对象json j;j["name"] = p.name;j["address"] = p.address;j["age"] = p.age;// 从json对象转换到结构体person p1{j["name"].get<std::string>(),j["address"].get<std::string>(),j["age"].get<int>()};cout << "------------------------------- 转换Json到结构体 END -------------------------------------------" << endl;
}int main()
{// 首先创建一个空的json对象json j; CreateVoidJson(j);//打印Json信息PrintJsonInfo(j);//输出Json文件OutputJson(j);//Json对象和C字符串相互转换,最长使用的场景JsonSwtichCString(j);// 读取一个json文件,nlohmann会自动解析其中数据ReadJsonFile();//任意类型转换JsonSwapType();return 0;
}
- 输出
------------------------------- 创建Json END -------------------------------------------3.141
Niels
42
1
0
2
"USD"
42.99
------------------------------- 输出Json信息END -------------------------------------------------------------------------- 导出Json END -------------------------------------------3.141
dump()返回 JSON 对象中存储的原始 string 值:{"happy":true,"pi":3.141}
------------------------------- Json字符串互转 END -------------------------------------------------------------------------- 读入Json END -------------------------------------------------------------------------- 转换Json到结构体 END -------------------------------------------
参考的文章:nlohmann入门使用总结
2.多层级Json读取
- 多层级Json举例
{"output": {"width": 720,"height": 1080,"frameRate": 20,"crf": 31},"tracks": [{"name": "t1","pieces": [{"file": "x.mp4","startTime": 2,"endTime": 6},{"file": "y.mp4","startTime": 9,"endTime": 13}]},{"name": "t2","pieces": [{"file": "z.mp4","startTime": 0,"endTime": 10}]}]
}
- C++代码解析
#include "nlohmann/json.hpp"
#include <fstream>
#include <iostream>using json = nlohmann::json;int main() {json j;std::ifstream jfile("test.json");jfile >> j;// 打印output对象【也可以用j["output"].at("width")】std::cout << j.at("output").at("width") << std::endl;std::cout << j.at("output").at("height") << std::endl;std::cout << j.at("output").at("frameRate") << std::endl;std::cout << j.at("output").at("crf") << std::endl;// 打印tracks数组对象for(int i=0; i<j["tracks"].size(); i++) {std::cout << j["tracks"][i].at("name") << std::endl;// 打印pieces子数组对象json j2 = j["tracks"][i].at("pieces");for(int k=0; k<j2.size(); k++) {std::cout << j2[k].at("file") << std::endl;std::cout << j2[k].at("startTime") << std::endl;std::cout << j2[k].at("endTime") << std::endl;}}return 0;
}
注:此部分代码参考1中的文章
3.推荐和参考:
rapidjson
- RapidJSON: 首页
- GitHub - Tencent/rapidjson: A fast JSON parser/generator for C++ with both SAX/DOM style API
nlohmann/json
- GitHub - nlohmann/json: JSON for Modern C++
- nlohmann入门使用总结