菜鸟笔记
提升您的技术认知

nlohmann/json 的用法示例-ag真人游戏

nlohmann/json 是一个c 实现的json解析器,使用非常方便直观。由于查看文档篇幅过长,不便于迅速阅读抓重点。而且,所举例的某些用法实践上其实比较少用到,而某些实践上常用到的一些用法,ag真人试玩娱乐官网却缺例子。所以自己简要总结了一下它的主要用法,并加上自己写的示例,希望能给到新接触该库的朋友一些帮助。

下载地址:

https://github.com/nlohmann/json/tree/develop/single_include/nlohmann/json.hpp

这是一个单独的c 头文件,所有的代码都在这个头文件里,实现代码都是内联实现,因此,只需要在cpp文件里包含这一个头文件即可。

引入头文件

#include "nlohmann/json.hpp"
using json = nlohmann::json;

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}
};

 3、解析与序列化

//解析
std::string s = r"(
    {
        "name": "judd trump",
        "credits": 1754500,
        "ranking": 1
    }
    )";
auto j = json::parse(s);
//序列化
std::string str = j.dump();

 4、解析文件

假设一个js文本文件 c:\test.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:\\test.json") >> j;

5、将json对象存为文件

json j;
std::ofstream("d:\\rankings.json") << j;

6、修改json对象

json j{
        { "name", "judd trump"},
        { "credits", 1754500 },
        {"ranking", 1}
    };
   
std::cout << j << endl;
j["name"] = "wang daniu"; //j.at("name") = "wang daniu";
   
std::cout << j << endl;

输出结果:

{"credits":1754500,"name":"judd trump","ranking":1}
{"credits":1754500,"name":"ding junhui","ranking":1}

7、与c 对象互相转换

struct player{
    string name;
    int credits;
    int ranking;
};
//1.重载转换函数
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);
}
//2.示例
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 players = j.get>();
std::cout << "name:    " << players[2].name << std::endl;
std::cout << "credits: " << players[2].credits << std::endl;
std::cout << "ranking: " << players[2].ranking << std::endl;
网站地图