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用以补获异常,这样比起一个一个元素去判断是否为空、是否为数组等要方便且安全!

相关推荐
wqfhenanxc22 分钟前
Mixing C++ and Rust for Fun and Profit 阅读笔记
c++·笔记·rust
R-G-B25 分钟前
【MFC】 VS2022打开低版本的MFC,双击.rc文件,DIalog加载失败,页面弹窗fatal error RC***:cannot open*****
c++·mfc·vs打开较早版本mfc·双击.rc文件·dialog加载失败·fatal error rc·cannot open
敲上瘾27 分钟前
基于Tcp协议的应用层协议定制
linux·运维·服务器·网络·c++·网络协议·tcp/ip
weixin_3077791327 分钟前
PySpark实现ABC_manage_channel逻辑
开发语言·python·spark
莹莹学编程—成长记1 小时前
string的模拟实现
服务器·c++·算法
??? Meggie1 小时前
【Python】保持Selenium稳定爬取的方法(防检测策略)
开发语言·python·selenium
酷爱码3 小时前
如何通过python连接hive,并对里面的表进行增删改查操作
开发语言·hive·python
画个大饼3 小时前
Go语言实战:快速搭建完整的用户认证系统
开发语言·后端·golang
喵先生!4 小时前
C++中的vector和list的区别与适用场景
开发语言·c++
Thomas_YXQ5 小时前
Unity3D Lua集成技术指南
java·开发语言·驱动开发·junit·全文检索·lua·unity3d