C++ 使用nlohmann/json.hpp库读写json字符串

1. json库

我个人比较喜欢 nlohmann/json.hpp 这个库,因为它只需要一个hpp文件即可,足够轻量!

这是它的github地址。

2. 简单实例代码

cpp 复制代码
#include <iostream>
#include <json.hpp>
#include <fstream>
#include <string>

using namespace nlohmann;
using namespace std;

string GenerateJsonStr()
{
    /*
    * 生成json格式字符串
    *
    * 预计的json格式文本为:
    * {
    *   "name": "ashui",
    *   "school": ["A school", "B school", "C school"],
    *   "money": [124.5, 345.3, 457.4],
    *
    *   physic
    *   {
    *       "height": 180,
    *       "weight": 68.5
    *   }
    * }
    */

    json json_data;
    json_data["name"] = "ashui";
    json_data["school"] = { "A school", "B school", "C school" };
    json_data["money"] = { 124.5, 345.3, 457.4 };

    json physic_data;
    physic_data["height"] = 180;
    physic_data["weight"] = 68.5;
    json_data["physic"] = physic_data;

    return json_data.dump();
}

bool SaveJsonStr()
{
    string jsonStr = GenerateJsonStr();

    // Save to file
    std::ofstream file("output.json");

    if (file.is_open())
    {
        file << jsonStr;

        file.close();

        std::cout << "dump string:" << std::endl;
        std::cout << jsonStr << std::endl;

        return true;
    }
    
    return false;
}

bool ReadJsonObj()
{
    std:ifstream jsonFile("D:\\Project\\C++\\json_example\\x64\\Debug\\output.json");

    if (!jsonFile.is_open())
    {
        std::cout << "Open json file error" << std::endl;
        return false;
    }

    json jsonData;
    try
    {
        jsonData = json::parse(jsonFile);

        if (jsonData.is_null())
        {
            std::cout << "The json object is null" << std::endl;
            return false;
        }

        std::string name = jsonData["name"];
        std::vector<std::string> school = jsonData["school"];
        std::vector<float> money = jsonData["money"];

        int height = jsonData["physic"]["height"];
        float weigjt = jsonData["physic"]["weight"];

        std::cout << std::endl;
        std::cout << "parse string:" << std::endl;
        std::cout << "name: " << name << std::endl;
        std::cout << "height: " << height << std::endl;
        std::cout << "weigjt: " << weigjt << std::endl;

        std::cout << "school: ";
        for (auto s : school)
        {
            std::cout << s << ", ";
        }
        std::cout << std::endl;

        std::cout << "money: ";
        for (auto m : money)
        {
            std::cout << m << ", ";;
        }
        std::cout << std::endl;
    }
    catch (const std::exception& e)
    {
        std::cout << "json error: "<< e.what() << std::endl;
        return false;
    }

    return true;
}

int main()
{
    SaveJsonStr();
    ReadJsonObj();
}

值得注意的是,在使用[]读取json内容时,最外层一定要套一个try-catch用以补获异常,这样比起一个一个元素去判断是否为空、是否为数组等要方便且安全!

相关推荐
程序喵大人2 分钟前
【C++入门】编译链接模型 - 07 链接器怎样把符号对上号
开发语言·c++·编译器·编译链接·链接器
微三云 - 廖会灵 (私域系统开发)13 分钟前
供应链系统实战:多渠道订单聚合与分布式库存一致性方案总结
开发语言·分布式·php
局部有解23 分钟前
Hot100 - 三数之和
数据结构·c++·算法
学逆向的38 分钟前
C 数据溢出与精度丢失
c语言·开发语言·网络安全
longlongzihan40 分钟前
C++ 常用数据结构速查:vector、stack、queue、list、树、图、哈希表等声明与核心操作
数据结构·c++·list
别动我齐刘海1 小时前
实时控制学习2
linux·c++·人工智能·学习·算法
霸道流氓气质1 小时前
AgentFlow 入门与实战:Task-Based 并发、EWMA 动态调度与四道门禁的 Java 生产级编排
java·开发语言
释厄6232 小时前
错误无误公理——错误正确本同源都迭代定律——逆转有价值
android·开发语言·kotlin
2601_962885722 小时前
如何用 Python计算 CR能量指标(中间意愿指标)?
开发语言·python
Dxy12393102162 小时前
MySQL JSON 生成列索引原理、实战与坑点
mysql·adb·json