json
https://github.com/nlohmann/json
官网仓库的test/src下边有很多例子可以参考,比如构造,解析等
说明
可以和 python,golang 的 json 库媲美了。 官网也支持单头文件的形式,坐标:官方仓库 single_include/nlohmann/json.hpp
用法
头文件
#include "nlohmann/json.hpp"
using json = nlohmann::json;
声明
json j1;
json j2 = json::object();
json j3 = json::array();
std::cout << j1.type_name() << std::endl; // output: null
std::cout << j2.type_name() << std::endl; // output: object
std::cout << j3.type_name() << std::endl; // output: array
构造
json j{
{ "name", "Judd Trump"},
{ "credits", 1754500 },
{ "ranking", 1}
};
解析及序列号
std::string s = R"(
{
"name": "Judd Trump",
"credits": 1754500,
"ranking": 1
}
)";
auto j = json::parse(s);
std::string s = j.dump();
读写文件
json j;
std::ifstream("c:\\rankings.json") >> j;
std::ofstream("d:\\rankings.json") << j;
读取及修改
json j{
{ "name", "Judd Trump"},
{ "credits", 1754500 },
{ "ranking", 1}
};
std::cout << j << endl; // {"credits":1754500,"name":"Judd Trump","ranking":1}
j["name"] = "Ding Junhui";
std::cout << j << endl; // {"credits":1754500,"name":"Ding Junhui","ranking":1}
//字典中查找key是否存在
auto subjectIdIter = j.find("name");
if (subjectIdIter != j.end()){
cout << "it is found" << endl;
}else{
cout << "not found " << endl;
}
//如果确定存在,直接可以访问. 直接访问如果不存在会触发抛出异常
std::cout<< j["name"] <<std::endl;
结构体和json互转
struct Player{
string name;
int credits;
int ranking;
};
void to_json(nlohmann::json& j, const Player& p) {
j = json{ {"name", p.name}, {"credits", p.credits}, {"ranking", p.ranking} };
}
void from_json(const nlohmann::json& j, Player& p) {
j.at("name").get_to(p.name);
j.at("credits").get_to(p.credits);
j.at("ranking").get_to(p.ranking);
}
auto j = R"([
{
"name": "Judd Trump",
"credits": 1754500,
"ranking": 1
},
{
"name": "Neil Robertson",
"credits": 1040500,
"ranking": 2
},
{
"name": "Ronnie O'Sullivan",
"credits": 954500,
"ranking": 3
}
])"_json;
std::vector<Player> players = j.get<std::vector<Player>>();
std::cout << "name: " << players[2].name << std::endl;
std::cout << "credits: " << players[2].credits << std::endl;
std::cout << "ranking: " << players[2].ranking << std::endl;
//name: Ronnie O'Sullivan
//credits: 954500
//ranking: 3
参考链接
|