“深入浅出”系列之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;
}
相关推荐
梁云亮12 小时前
Jquery ajax 提交序列化或JSON数据到后台
json·jquery·序列化
qq_427506082 天前
npm下载插件无法更新package.json和package-lock.json文件的解决办法
前端·npm·json
农民也会写代码2 天前
php将json数据保存在MySQL中并读取
mysql·json·php
Stay Passion3 天前
Java实用注解篇: @JSONField
java·开发语言·json
南郁3 天前
005-nlohmann/json 基础方法-C++开源库108杰
c++·开源·json
别催小唐敲代码3 天前
解决跨域的4种方法
java·服务器·前端·json
橙色小博3 天前
Python中的JSON库,详细介绍与代码示例
数据库·python·json
龙虎榜小红牛系统3 天前
Python项目源码57:数据格式转换工具1.0(csv+json+excel+sqlite3)
python·json·excel
wtsolutions3 天前
在Excel中轻松处理嵌套JSON数据:json-to-excel插件使用指南
json·excel·nested·嵌套·json-to-excel
秋风&萧瑟4 天前
【QT】QT中http协议和json数据的解析-http获取天气预报
qt·http·json