C++中如何使用JSON

在C++中使用JSON,首先需要导入JSON库。

这里我们使用的是nlohmann/json库,这个库只需要引用其提供的json.hpp文件即可使用,没有任何依赖,也不需要复杂的构建过程。

下载

点击此处可以下载 JSON for Modern C++ version 3.11.3

需要其他版本可以查看Github仓库release

将其放置在编译可寻地址(最简单的是放在源文件的目录下)。

别名

#include "json.hpp"
// 使用json作为nlohmann::json的别名
using json = nlohmann::json;

序列化

string serialization() {
    // 声明一个nlohmann::json对象。
    json js;

    // 添加三个项
    js["id"] = 1;
    js["name"] = "CodeSingerAlex";
    js["password"] = "password";

    // 将nlohmann::json对象转换为JSON格式的字符串。
    string request = js.dump();
    
    cout << request << endl;
    return request;
}

反序列化

void deserialization(string &request) {
    json js = json::parse(request);
    std::cout << js["id"] << std::endl;
    std::cout << js["name"] << std::endl;
    std::cout << js["password"] << std::endl;
}

完整代码

#include "json.hpp"
#include <iostream>
#include <string>
using namespace std;
using json = nlohmann::json;

string serialization() {
    // 声明一个nlohmann::json对象。
    json js;

    // 添加三个项
    js["id"] = 1;
    js["name"] = "CodeSingerAlex";
    js["password"] = "password";

    // 将nlohmann::json对象转换为JSON格式的字符串。
    string request = js.dump();

    cout << request << endl;
    return request;
}

void deserialization(string &request) {
    // 将request解析为nlohmann::json对象。
    json js = json::parse(request);

    // 输出对应键的值
    std::cout << js["id"] << std::endl;
    std::cout << js["name"] << std::endl;
    std::cout << js["password"] << std::endl;
}
int main() {
    string request = serialization();
    deserialization(request);
}

注意编译是需要加-std=c++11选项,因为nlohmann/json库是用C++11编写的,编译命令类似:

g++ -std=c++11 jsontest.cpp -o jsontest 

输出

{"id":1,"name":"CodeSingerAlex","password":"password"}
1
"CodeSingerAlex"
"password"
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值