> 文章列表 > json for modern c++

json for modern c++

json for modern c++

目录

  • json for modern c++
    • 概述
    • 编译问题
      • 问题描述
      • 问题解决
    • 读取JSON文件demo

json for modern c++

GitHub - nlohmann/json: JSON for Modern C++

概述

json for modern c++是一个德国大牛nlohmann写的,该版本的json有以下特点:
1.直观的语法。
2.整个代码由一个头文件组成json.hpp,没有子项目,没有依赖关系,没有复杂的构建系统,使用起来非常方便。
3.使用c++11标准编写。
4.使用json 像使用STL容器一样。
5.STL和json容器之间可以相互转换。

编译问题

问题描述

看所有文章,都是写下载该工程,把json.hpp包含即可。如下图所示
json for modern c++
json for modern c++

结果编译不过,编译报错如下图所示
json for modern c++

问题解决

后查找资料,查到该JSON库有个Issues中提到了该问题,并解决了。
‘nlohmann/json.hpp’ file not found · Issue #2188 · nlohmann/json · GitHub
json for modern c++

后续按照人提供的思路,输入指令sudo apt install nlohmann-json-dev 即可编译通过

读取JSON文件demo

参考文章:
JSON for Modern C++ 库的介绍与使用示例代码_mordenjson
示例代码如下所示:

#include <iostream>
#include <fstream>
#include <nlohmann/json.hpp>using json = nlohmann::json;/simple.json 文件
{"ok":true,"height": 20.123,"width": 1000,"name": "test"
}*/int main()
{json j;                             // json 对象std::ifstream jfile("simple.json"); // 流读取jfile >> j;                         // 文件流形式读取 json 文件, 并存为 jjfile.close();std::cout << "json j = " << j << std::endl;bool ok = j.at("ok");float height = j["height"];int width = j["width"];std::string name = j.at("name");std::cout << "ok = " << ok << std::endl;std::cout << "height = " << height << std::endl;std::cout << "width = " << width << std::endl;std::cout << "name = " << name << std::endl;return 0;
}

运行结果如下图所示
json for modern c++