1. nlohmann-json
里边包含单头文件项目,只需要引入头文件 json.hpp 就可以使用使用,特别试用于demo
说明:可以和 python,golang 的 json 库媲美了。官网也支持单头文件的形式
1.1. 定义类型
#include "nlohmann/json.hpp"
using json = nlohmann::json;
json j1;
json j2 = json::object();
json j3 = json::array();
std::cout << j1.type_name();
1.2. 构造 json 结构
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include "nlohmann/json.hpp"
using json = nlohmann::json;
using namespace std;
// 从文件构建
json data;
ifstream("test.json") >> data;
//从字符串构建
std::string s = R"(
{
"name": "first name",
"credits": 1754500,
"ranking": {
"name": "seconde name",
"info": [ "1","2","3"]
}
}
)";
data = json::parse(s);
//读取数据,通过下标或者key获取的类型都是 json 格式
cout<<data["name"].get<string>()<<endl; //first name
vector<string> info = data["ranking"]["info"].get<vector<string>>(); //[ "1","2","3"]
1.3. 和结构体关联
#include <string>
#include "nlohmann/json.hpp"
using json = nlohmann::json;
struct Player{
std::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);
}
int main(){
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;
return 0;
}