“深入浅出”系列之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;
}
相关推荐
Java成神之路-1 天前
SpringMVC 响应实战指南:页面、文本、JSON 返回全流程(Spring系列13)
java·spring·json
我命由我123451 天前
在 React 项目中,可以执行 npm start 命令,但是,无法执行 npm build 命令
前端·javascript·vue.js·react.js·前端框架·json·ecmascript
带刺的坐椅1 天前
RFC 9535:JSONPath 的标准化之路
java·json·jsonpath·snack4·rfc9535
孙同学20201 天前
如何将 JSON 数据转换为 Excel 工作表
python·json·excel
ID_180079054732 天前
除了 Python,还有哪些语言可以解析 JSON 数据?
开发语言·python·json
电商API&Tina2 天前
跨境电商如何接入1688官方寻源通接口?附接入流程
java·数据库·python·sql·oracle·json·php
神の愛3 天前
利用json-to-ts工具进行转换,放置在typeScript.ts文件中
javascript·typescript·json
BUG_MeDe3 天前
从Json对象中提取某个对象的一点注意--libjson-c
linux·json
HelloTonyGo3 天前
个人游戏笔记本免费“养龙虾”(七)OpenClaw的openclaw.json文件的基本配置
ubuntu·json·配置·读写权限·openclaw
数据知道4 天前
claw-code 源码详细分析:`reference_data` JSON 快照——大型移植里「对照底稿」该怎么治理与演进?
linux·python·ubuntu·json·claude code