“深入浅出”系列之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;
}
相关推荐
Risehuxyc1 天前
前端同学,你能不能别再往后端传一个巨大的JSON了?
前端·json·状态模式
逢五必更2 天前
从json中提取i18n字段
json
二楼后座。3 天前
Golang操作MySQL json字段优雅写法
mysql·golang·json
wtsolutions4 天前
Excel to JSON API by WTSolution Documentation
json·excel·api·wtsolutions
面朝大海,春不暖,花不开5 天前
结构化数据格式解析:JSON 与 XML 的技术应用与实践
xml·json
PythonicCC6 天前
Django核心知识点详解:JSON、AJAX、Cookie、Session与用户认证
ajax·django·json
-凌凌漆-6 天前
【Qt】Qt QML json处理
开发语言·qt·json
racerun6 天前
UniApp中的pages.json 和 tabBar
uni-app·json
我命由我123457 天前
前端开发问题:SyntaxError: “undefined“ is not valid JSON
开发语言·前端·javascript·vue.js·json·ecmascript·js
Code季风7 天前
将 gRPC 服务注册到 Consul:从配置到服务发现的完整实践(上)
数据库·微服务·go·json·服务发现·consul