“深入浅出”系列之C++:(10)nlohmann Json库

一、简介

nlohmann Json库为C++开发者提供了一种高效、便捷的方式来处理JSON数据。通过简洁的语法、丰富的功能和良好的性能,它成为了C++项目中处理JSON数据的首选库。无论是简单的JSON对象创建与解析,还是复杂的嵌套结构处理、自定义类型的序列化与反序列化,nlohmann Json库都能轻松应对。

简洁易用的语法:nlohmann Json库的语法设计非常直观,类似于C++标准库中的容器操作。

高性能:该库在性能方面表现出色,经过了精心的优化。无论是解析大型JSON文档还是生成JSON数据,都能高效完成。

丰富的功能:支持从文件、字符串中读取和写入JSON数据,支持JSON数据的序列化和反序列化,还能方便地进行JSON数据的遍历、修改和查询。

严格的标准遵循:nlohmann Json库严格遵循JSON标准,确保生成和解析的JSON数据符合规范

二、代码

1、创建json对象

复制代码
#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() {
    // 创建一个空的JSON对象
    json j;
    // 添加键值对
    j["name"] = "John";
    j["age"] = 30;
    j["city"] = "New York";

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

2、解析json字符串

复制代码
#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() {
    std::string jsonString = R"({"name": "Jane", "age": 25, "city": "London"})";
    json j = json::parse(jsonString);

    std::cout << "Name: " << j["name"] << std::endl;
    std::cout << "Age: " << j["age"] << std::endl;
    std::cout << "City: " << j["city"] << std::endl;

    return0;
}

3、从文件读取和写入JSON数据

复制代码
#include <iostream>
#include <fstream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() {
    // 从文件读取JSON数据
    std::ifstream inputFile("data.json");
    json j;
    inputFile >> j;
    inputFile.close();

    std::cout << "Read from file: " << j.dump(4) << std::endl;

    // 修改JSON数据
    j["newKey"] = "New Value";

    // 将修改后的数据写入文件
    std::ofstream outputFile("newData.json");
    outputFile << std::setw(4) << j << std::endl;
    outputFile.close();

    return0;
}

4、处理JSON数组

复制代码
#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() {
    // 创建一个包含数组的JSON对象
    json j;
    j["fruits"] = {"apple", "banana", "cherry"};

    // 遍历数组
    for (constauto& fruit : j["fruits"]) {
        std::cout << fruit << std::endl;
    }

    return0;
}

5、嵌套JSON结构

复制代码
#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() {
    // 创建一个嵌套的JSON结构
    json j;
    j["person"] = {
        {"name", "Alice"},
        {"age", 28},
        {"address", {
            {"street", "123 Main St"},
            {"city", "Anytown"},
            {"country", "USA"}
        }}
    };

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

    // 访问嵌套的值
    std::cout << "City: " << j["person"]["address"]["city"] << std::endl;

    return0;
}

6、JSON数据的序列化与反序列化

复制代码
#include <iostream>
#include <nlohmann/json.hpp>
#include <vector>

using json = nlohmann::json;

// 自定义结构体
struct Point {
    double x;
    double y;
};

// 为自定义结构体提供序列化和反序列化支持
void to_json(json& j, const Point& p) {
    j = json{
  
  {"x", p.x}, {"y", p.y}};
}

void from_json(const json& j, Point& p) {
    p.x = j.at("x");
    p.y = j.at("y");
}

int main() {
    // 创建一个包含自定义结构体的向量
    std::vector<Point> points = { {1.0, 2.0}, {3.0, 4.0} };

    // 序列化向量为JSON
    json j = points;

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

    // 反序列化JSON为向量
    std::vector<Point> newPoints = j.get<std::vector<Point>>();

    for (constauto& point : newPoints) {
        std::cout << "(" << point.x << ", " << point.y << ")" << std::endl;
    }

    return0;
}

7、使用迭代器遍历JSON对象

复制代码
#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() {
    json j = {
        {"name", "Bob"},
        {"age", 35},
        {"hobbies", {"reading", "painting"}}
    };

    // 使用迭代器遍历JSON对象
    for (json::iterator it = j.begin(); it!= j.end(); ++it) {
        std::cout << it.key() << ": ";
        if (it.value().is_array()) {
            for (constauto& element : it.value()) {
                std::cout << element << " ";
            }
        } else {
            std::cout << it.value();
        }
        std::cout << std::endl;
    }

    return0;
}
相关推荐
凌晨一点的秃头猪2 小时前
Python JSON 模块核心函数超详细指南
json
小江的记录本4 小时前
【JWT】JWT(JSON Web Token)结构化知识体系(完整版)
前端·网络·web安全·http·网络安全·json·安全架构
早點睡3905 小时前
ReactNative项目OpenHarmony三方库集成实战:react-native-json-tree
react native·react.js·json
清水白石00814 小时前
Python 对象序列化深度解析:pickle、JSON 与自定义协议的取舍之道
开发语言·python·json
晨欣1 天前
如何根据 config.json 核对 MoE 模型的激活参数:以 gpt-oss-120b 为例(GPT-5.4-high 生成)
gpt·大模型·json·openai
带刺的坐椅1 天前
Snack4 Json 流式解析与自动结构修复深度指南
java·llm·json·jsonpath
m0_584624501 天前
调用接口返回的json数据被截断
java·json
ID_180079054732 天前
模拟1688商品详情的Python API实现,返回符合风格的JSON数据
开发语言·python·json
KingCruel2 天前
MySQL JSON 数据操作
mysql·json
2601_953465612 天前
HLS.js 原生开发!m3u8live.cn打造最贴合项目的 M3U8 在线播放器
开发语言·前端·javascript·python·json·ecmascript·前端开发工具