今天在找可以在C++中用的JSON库。
一个比较好用的传统的JSON库是JsonCpp
, GitHub地址:jsoncpp: A C++ library for interacting with JSON.。但是安装起来比较麻烦:
sudo apt-get install libjsoncpp-dev
sudo ln -s /usr/include/jsoncpp/json/ /usr/include/json
我选择了另外一个库,叫JSON for Modern C++
,GitHub地址:nlohmann/json: JSON for Modern C++。
这个库最大的优点是只要包含一个库文件就可以了,非常方便
在Releases 中下载单文件的json.hpp
:Releases · nlohmann/json
运行示例如下:
#include <iostream>
#include <fstream>
#include <iomanip>
#include "json.hpp"
using namespace std;
using json = nlohmann::json;
int main(int argc, char **argv) {
cout << "test start " << endl;
// create an empty structure (null)
json j;
// add a number that is stored as double (note the implicit conversion of j to an object)
j["pi"] = 3.141;
// add a Boolean that is stored as bool
j["happy"] = true;
// add a string that is stored as std::string
j["name"] = "Niels";
// add another null object by passing nullptr
j["nothing"] = nullptr;
// add an object inside the object
j["answer"]["everything"] = 42;
// add an array that is stored as std::vector (using an initializer list)
j["list"] = {1, 0, 2};
// add another object (using an initializer list of pairs)
j["object"] = {{"currency", "USD"},
{"value", 42.99}};
// instead, you could also write (which looks very similar to the JSON above)
json j2 = {
{"pi", 3.141},
{"happy", true},
{"name", "Niels"},
{"nothing", nullptr},
{"answer", {
{"everything", 42}
}},
{"list", { 1, 0, 2}},
{"object", {
{"currency", "USD"},
{"value", 42.99}
}}
};
string jsonFile = "new_tree.json";
std::ofstream outFile(jsonFile);
outFile << std::setw(4) << j << std::endl;
std::cout << j.dump(4) << std::endl;
}
文档信息
- 本文作者:last2win
- 本文链接:https://last2win.com/2019/06/17/json/
- 版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)