JSON做爲當下流行的數據交換語言,其易於人閱讀和編寫,易於機器解析和生成,以及高效的網絡傳輸效率等特性,使其再互聯網、物聯網等行業獲得了普遍的使用,使用JSON做爲配置文件的項目也是多不勝數(不過C++好像少一點),筆者正好最近在作物聯網相關的項目,在學着使用JSON,索性就先用JSON作一下本身項目的配置文件。ios
進入JSON官網或者直接在github上搜索,均可以找到大量的JSON庫,筆者今天選擇的是人氣最旺 nlohmann/json,因爲配置文件對速度和內存沒有特殊的要求,因此主要考慮的就是易用性了。git
github地址:github.com/nlohmann/jsongithub
因爲 nlohmann/json 使用 C++ 11,因此要支持C++ 11 的開發環境,引用官方文檔:json
Though it's 2019 already, the support for C++11 is still a bit sparse. Currently, the following compilers are known to work:網絡
筆者公司的電腦是 Visual C++ 2015,編譯 examples 是編譯不過的,應該是編譯工具版本致使的,改天再研究。今天筆者用的是本身家裏的電腦,開發環境是 Microsoft Visual C++ 2017app
// #include "pch.h" #include <iostream> #include "nlohmann/json.hpp" // https://github.com/nlohmann/json/tree/develop/single_include/nlohmann/json.hpp #include <fstream> // ifstream, ofstream #include <iomanip> // std::setw() using json = nlohmann::json; int main() { // 從文件讀取配置 std::ifstream fin("config.json"); // 注意此處是相對路徑 json j; fin >> j; fin.close(); // 檢查讀取的和預期的是否一致 std::cout << j["pi"] << std::endl; // 3.141 std::cout << j["happy"] << std::endl; // true std::cout << j["name"] << std::endl; // "Niels" std::cout << j["nothing"] << std::endl; // null std::cout << j["answer"]["everything"] << std::endl; // 42 std::cout << j["list"] << std::endl; // [1, 0, 2] std::cout << j["object"] << std::endl; // { "currency":"USD","value" : 42.99 } // 寫入文件 std::ofstream fout("object.json"); // 注意 object.json 和 config.json 內容一致,可是順序不一樣 fout << std::setw(4) << j << std::endl; fout.close(); // 注意: // JSON標準將對象定義爲「零個或多個名稱 / 值對的無序集合」。 // 若是但願保留插入順序,能夠使用tsl::ordered_map(integration)或nlohmann::fifo_map(integration)等容器專門化對象類型。 getchar(); }
config.json工具
{ "pi": 3.141, "happy": true, "name": "Niels", "nothing": null, "answer": { "everything": 42 }, "list": [ 1, 0, 2 ], "object": { "currency": "USD", "value": 42.99 } }