nlohmann::json的使用非常简单,只需要包含.hpp文件即可,这是它的官网https://github.com/nlohmann/json
简单使用:
#include "json.hpp"
#include <iostream>
using Info = nlohmann::json;
int main()
{
Info info;
std::cout << info.size() << std::endl;
info["a"] = "b";
std::cout << info["a"] << std::endl;
auto iter = info.find("a");
if (iter == info.end()) {
std::cout << "not found" << std::endl;
}
else {
std::cout << *iter << std::endl;
}
std::string s = R"({
"name" : "nick",
"credits" : "123",
"ranking" : 1
})";
auto j = nlohmann::json::parse(s);
std::cout << j["name"] << std::endl;
std::string ss = j.dump();
std::cout << "ss : " << ss << std::endl;
Info j1;
Info j2 = nlohmann::json::object();
Info j3 = nlohmann::json::array();
std::cout << j1.is_object() << std::endl;
std::cout << j1.type_name() << std::endl;
std::cout << j2.is_object() << std::endl;
std::cout << j2.is_array() << std::endl;
Info infoo{
{"name", "darren"},
{"credits", 123},
{"ranking", 1}
};
std::cout << infoo["name"] << std::endl;
std::cout << infoo.type_name() << std::endl;
//遍历
for (auto iter = infoo.begin(); iter != infoo.end(); iter++) {
std::cout << iter.key() << " : " << iter.value() << std::endl;
//std::cout << iter.value() << std::endl;
//std::cout << *iter << std::endl;
}
system("pause");
return 0;
}
输出:
最近发现了一个问题,就是它默认会对键进行排序,那如果不想让它排序怎么办?
可以看一下官网的文档
可以看到这里说的很详细,这里提供两种方法:
std::vector<std::pair<std::string, int>> keyValuePairs;
keyValuePairs.emplace_back("key3", 3);
keyValuePairs.emplace_back("key1", 1);
keyValuePairs.emplace_back("key2", 2);
nlohmann::json jsonObject(keyValuePairs);
// 输出序列化后的JSON数据
std::cout << jsonObject.dump() << std::endl;
std::cout << "===============" << std::endl;
nlohmann::ordered_json orderjson;
orderjson["a"] = 1;
orderjson["c"] = 2;
orderjson["b"] = 3;
std::cout << orderjson.dump(2) << std::endl;