推荐一个好用的C++ json库:nlohmann json

Qt自带的json库功能很强大,为什么还要用第三方json库呢?因为直接也做嵌入式开发,有些嵌入式系统不需要界面,移植Qt就不太合适了,这时候第三方json库就派上用场了。
nlohmann json是我用过的一个C++ json库,github地址:https://github.com/nlohmann/json

一.特点

1.直观的语法
在Python等语言中,JSON使用非常直观高效。nlohmann json使用现代C++实现了类似的语法。
2.方便的整合
我们的整个代码由一个头文件组成json.hpp文件. 就这样。没有库,没有子项目,没有依赖关系,没有复杂的构建系统。该类是用C++ 11编写的。总之,一切都不需要调整编译器标志或项目设置。
3.认真的测试
我们的类经过了严格的单元测试,涵盖了100%的代码,包括所有异常行为。此外,我们还使用Valgrind和Clang Sanitizers进行检测,没有内存泄漏。为了保持高质量,项目遵循核心基础设施倡议(CII)最佳实践( Core Infrastructure Initiative (CII) best practices.)

其他方面对我们来说并不那么重要:

1.内存效率
每个JSON对象都有一个指针和一个枚举(1字节)的开销。默认泛型使用以下C++数据类型:字符串使用std::string;数字使用int64_t、uint64_t或double;对象使用std::map;数组使用std::vector;布尔类型使用bool。但是,您可以根据自己的需要对通用类basic_json进行模板化。
2.速度
当然还有更快的JSON库。但是,如果您的目标是通过添加单个头文件的JSON库来加快开发速度,那么这个库就是一个不错的选择。如果您知道如何使用std::vector或std::map,那么就再好不过了,因为此库支持json和std::vector、std::map的相互转换。

二.用法举例

如果想创建如下json对象:

{
  "pi": 3.141,
  "happy": true,
  "name": "Niels",
  "nothing": null,
  "answer": {
    "everything": 42
  },
  "list": [1, 0, 2],
  "object": {
    "currency": "USD",
    "value": 42.99
  }
}

那么通过下面两种方法可以实现:
方法一:

#include <nlohmann/json.hpp>
using json = nlohmann::json;
// create an empty structure (null)
json j;
// add a number that is stored as double (note the implicit conversion of j to an object)
j["pi"] = 3.141;
// add a Boolean that is stored as bool
j["happy"] = true;
// add a string that is stored as std::string
j["name"] = "Niels";
// add another null object by passing nullptr
j["nothing"] = nullptr;
// add an object inside the object
j["answer"]["everything"] = 42;
// add an array that is stored as std::vector (using an initializer list)
j["list"] = { 1, 0, 2 };
// add another object (using an initializer list of pairs)
j["object"] = { {"currency", "USD"}, {"value", 42.99} };

方法二:

#include <nlohmann/json.hpp>
using json = nlohmann::json;
json j2 = {
  {"pi", 3.141},
  {"happy", true},
  {"name", "Niels"},
  {"nothing", nullptr},
  {"answer", {
    {"everything", 42}
  }},
  {"list", {1, 0, 2}},
  {"object", {
    {"currency", "USD"},
    {"value", 42.99}
  }}
};

更详细的使用方法可参考官网demo

原创不易,转载请标明出处:推荐一个好用的C++ json库:nlohmann json_草上爬的博客-CSDN博客

  • 8
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

草上爬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值