C++: visual studio加载nlohmann/json库及json库使用方法介绍

一、visual studio加载nlohman/json库

nlohmann/json 是一个 单头文件(header-only) 的库,所以你可以 直接下载 json.hpp 并包含它,而不需要额外的编译和链接步骤。

步骤 1:下载 json.hpp

  1. 下载 JSON for Modern C++

    • 访问 官方 GitHub

    • 找到 json.hpp(在 single_include/nlohmann/ 目录下)

    • 下载并保存到你的项目目录,例如:D:\Projects\MyProject\include\nlohmann\json.hpp

步骤 2:包含 json.hpp

在你的 C++ 代码中添加:

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

int main() {
    json j = {{"name", "Alice"}, {"age", 25}, {"city", "New York"}};
    std::cout << j.dump(4) << std::endl;
    return 0;
}

步骤 3:配置 Visual Studio 的 Include Path

如果 json.hpp 没有放在 项目的同级目录,你需要手动设置 包含目录

  1. Visual Studio 2019 中,右键 项目,选择 属性(Properties)

  2. C/C++ → 常规(General) 选项卡下:

    • 找到 附加包含目录(Additional Include Directories)

    • 添加 D:\Projects\MyProject\include

  3. 点击 应用(Apply)确定(OK)

二、使用方法介绍

1. 引入 JSON 库

首先,在代码中包含 json.hpp

#include <iostream>
#include "nlohmann/json.hpp"

// 使用 json 命名空间,简化调用
using json = nlohmann::json;

2. 创建 JSON

(1)从 std::mapstd::vector 构造 JSON

json j = {
    {"name", "Alice"},
    {"age", 25},
    {"city", "New York"},
    {"skills", {"C++", "Python", "Java"}},
    {"details", {{"height", 1.75}, {"weight", 65}}}
};

std::cout << j.dump(4) << std::endl;  // 输出格式化 JSON

输出:

{
    "name": "Alice",
    "age": 25,
    "city": "New York",
    "skills": ["C++", "Python", "Java"],
    "details": {
        "height": 1.75,
        "weight": 65
    }
}

3. 访问 JSON 数据

(1)使用 [] 访问

std::string name = j["name"];
int age = j["age"];
std::cout << "Name: " << name << ", Age: " << age << std::endl;

(2)使用 .at() 访问(推荐,避免异常)

std::string city = j.at("city");
std::cout << "City: " << city << std::endl;

(3)访问嵌套 JSON

double height = j["details"]["height"];
std::cout << "Height: " << height << "m" << std::endl;

(4)访问数组

std::string firstSkill = j["skills"][0];
std::cout << "First Skill: " << firstSkill << std::endl;

4. 修改 JSON

j["age"] = 30;  // 修改值
j["skills"].push_back("JavaScript");  // 添加数组元素
j["details"]["weight"] = 70;  // 修改嵌套字段

std::cout << j.dump(4) << std::endl;

5. 删除 JSON 字段

j.erase("city");  // 删除 key "city"
std::cout << j.dump(4) << std::endl;

6. JSON 转换为字符串

(1)格式化输出

std::string jsonStr = j.dump(4);  // 4 表示缩进空格
std::cout << jsonStr << std::endl;

(2)紧凑格式

std::string compactStr = j.dump();
std::cout << compactStr << std::endl;

7. 字符串解析 JSON

(1)从 JSON 字符串创建 JSON 对象

std::string jsonText = R"({"name": "Bob", "age": 28, "city": "London"})";
json j2 = json::parse(jsonText);
std::cout << "Name: " << j2["name"] << std::endl;

8. 判断 JSON 是否包含某个字段

if (j.contains("age")) {
    std::cout << "Age exists: " << j["age"] << std::endl;
}

9. 遍历 JSON

(1)遍历对象

for (auto& [key, value] : j.items()) {
    std::cout << key << ": " << value << std::endl;
}

(2)遍历数组

for (auto& skill : j["skills"]) {
    std::cout << "Skill: " << skill << std::endl;
}

10. JSON 序列化到文件

#include <fstream>

std::ofstream file("output.json");
file << j.dump(4);
file.close();

11. 读取 JSON 文件

#include <fstream>

std::ifstream file("output.json");
json j3;
file >> j3;
std::cout << "Read from file: " << j3.dump(4) << std::endl;

12. C++ 结构体与 JSON 互转

(1)定义结构体

struct Person {
    std::string name;
    int age;
};

// 让 nlohmann::json 支持 Person 结构体
void to_json(json& j, const Person& p) {
    j = json{{"name", p.name}, {"age", p.age}};
}

void from_json(const json& j, Person& p) {
    p.name = j.at("name").get<std::string>();
    p.age = j.at("age").get<int>();
}

(2)结构体转 JSON

Person p1{"Alice", 25};
json j4 = p1;
std::cout << j4.dump(4) << std::endl;

(3)JSON 转 结构体

std::string jsonStr = R"({"name": "Bob", "age": 30})";
json j5 = json::parse(jsonStr);
Person p2 = j5.get<Person>();
std::cout << "Person Name: " << p2.name << ", Age: " << p2.age << std::endl;

13.判断是否包含某Key

if (j.contains("age") && !j["age"].is_null()) {
    std::cout << "age is not null!" << std::endl;
} else {
    std::cout << "age is null or does not exist!" << std::endl;  // ✅ age 为 null
}

14.判断某个key的value是否为某数据类型

if (j.contains("age") && j["age"].is_number()) {
    std::cout << "age is a number!" << std::endl;
}
if (j.contains("name") && j["name"].is_string()) {
    std::cout << "name is a string!" << std::endl;
}

总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值