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

相关推荐
枫叶梨花17 分钟前
使用Go语言获取Windows系统信息:从CPU到电池的全维度监控
开发语言·windows·golang
C_Liu_21 分钟前
从C语言到C++:拥抱面向对象编程的全新世界
c语言·开发语言·c++
哈基咩24 分钟前
Go 语言模糊测试 (Fuzz Testing) 深度解析与实践
开发语言·后端·golang
元气少女小圆丶26 分钟前
Mirror学习笔记
java·开发语言·学习
lly20240628 分钟前
Perl 面向对象编程深入解析
开发语言
瓦特what?33 分钟前
C + +
c语言·开发语言·c++·经验分享·笔记·算法·程序员创富
@十八子德月生34 分钟前
第三阶段—8天Python从入门到精通【itheima】-143节(pyspark实战——数据计算——flatmap方法)
大数据·开发语言·python·数据分析·pyspark·好好学习,天天向上·question answer
爱编码的程序员39 分钟前
python 处理json、excel、然后将内容转化为DSL语句,适用于数据处理(实用版)
人工智能·python·ai·json·excel·数据处理·dsl
沐知全栈开发1 小时前
C# 运算符重载
开发语言
天机️灵韵1 小时前
开源医院信息管理系统:基于若依框架的智慧医疗解决方案
java·开发语言·spring boot·spring cloud·github·开源项目