C++的nlohmann-json

1. nlohmann-json

git网址

里边包含单头文件项目,只需要引入头文件 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值