“深入浅出”系列之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;
}
相关推荐
njsgcs21 小时前
json转excel python pd
python·json·excel·pd
代码搬运媛1 天前
【架构相关】tsconfig.json 与 tsconfig.node.json、tsconfig.app.json 的关系和作用
node.js·json
aerror3 天前
json转excel xlsx文件
开发语言·python·json
掉鱼的猫3 天前
全球首个支持 IETF JSONPath (RFC 9535) 标准的 Java 框架,Snack4-Jsonpath v4.0.0 发布
java·json
吹个口哨写代码3 天前
处理文本编辑器存的json格式报错问题,对编辑器存的字段进行转换处理,再通过json返回
java·编辑器·json
APIshop4 天前
代码实例:Python 爬虫抓取与解析 JSON 数据
爬虫·python·json
得物技术4 天前
从 JSON 字符串到 Java 对象:Fastjson 1.2.83 全程解析|得物技术
java·后端·json
GISBox5 天前
GISBox如何让GeoTIFF突破Imagery Provider加载限制?
react.js·json·gis
C嘎嘎嵌入式开发5 天前
(20)100天python从入门到拿捏《JSON 数据解析》
开发语言·python·json
LazerYvTian5 天前
Json数据字段类型兼容性处理
json