前言
nlohmann/json 是一个用于解析json的开源c++库,口碑一流,号称有业界最好的性能,并且使用非常方便直观,是很多c++程序员的首选。开源官网处有详细说明用法,但篇幅过长,不便于迅速阅读抓重点。而且,所举例的某些用法实践上其实比较少用到,而某些实践上常用到的一些用法,官网却缺例子。所以自己简要总结了一下它的主要用法,并加上自己写的示例,希望能给到新接触该库的朋友一些帮助。
准备工作
下载https://github.com/nlohmann/json/tree/develop/single_include/nlohmann/json.hpp, 并加入本地工程
引用头文件
#include "nlohmann/json.hpp" using json = nlohmann::json;
主要用法:
#1 声明与构造
##1 纯粹声明
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
##2 内容构造
json j = R"( { "name": "Judd Trump", "credits": 1754500, "ranking": 1 } )"_json;
或
json j{ { "name", "Judd Trump"}, { "credits", 1754500 }, { "ranking", 1} };
#2 解析与序列化
字符串:
解析
std::string s = R"( { "name": "Judd Trump", "credits": 1754500, "ranking": 1 } )"; auto j = json::parse(s);
序列化
std::string s = j.dump();
文件:// 比如有文件 c:\rankings.json,其内容如下
[ { "name": "Judd Trump", "credits": 1754500, "ranking": 1 }, { "name": "Neil Robertson", "credits": 1040500, "ranking": 2 }, { "name": "Ronnie O'Sullivan", "credits": 954500, "ranking": 3 } ]
解析:
json j; std::ifstream("c:\\rankings.json") >> j;
序列化
std::ofstream("d:\\rankings.json") << j;
#3 引用和修改
举个栗子:
json j{ { "name", "Judd Trump"}, { "credits", 1754500 }, { "ranking", 1} }; std::cout << j << endl; j["name"] = "Ding Junhui"; //j.at("name") = "Ding Junhui"; std::cout << j << endl;
输出结果:
{"credits":1754500,"name":"Judd Trump","ranking":1} {"credits":1754500,"name":"Ding Junhui","ranking":1}
#4 转换成C++对象
定义对象类型
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