简单好用的C++ json库——JSON for Modern C++

github传送门为:https://nlohmann.github.io/json/

简介

首先这个库不是奔着性能去的,设计者考虑的是:直观的语法(Intuitive syntax)、微小的整合(Trivial integration)、认真的测试(Serious testing)

至于内存效率和速度,反倒不是优先考虑的。

先说说微小的整合。在项目中只需要包含一个json.hpp的单个头文件就可以了,为了便于编程,使用命名空间会更加方便:

1
2
3
#include <json.hpp>
//...
using json = nlohmann::json;

  

火线入门

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <fstream>
#include <iomanip>
#include "json.hpp"
 
using namespace std;
using json = nlohmann::json;
     
int main()
{
    cout<<"Json test"<<endl;
 
    json j;
    j["name"]="castor";
    j["sex"]="male";
    j["age"]=12;
    cout<<j<<endl;
 
    string s="xdfile.json";
    ofstream outFile(s);
    outFile<<setw(4)<<j<<endl;
     
    return 0;
}

  可以看到,使用起来还是非常直观的,json类就像是一个cpp的原生类一样方便操作,还重载了<<。所写的文件打开如下:

 同时也会发现, json对键进行了排序,应该是使用了map的缘故。

  

从字符串到Json对象

通过字符串解析:

 一种方式是使用_json:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <fstream>
#include <iomanip>
#include "json.hpp"
 
using namespace std;
using json = nlohmann::json;
     
int main()
{
    cout<<"Json test"<<endl;
    json j;
    j="{ \"happy\": true, \"pi\": 3.141 }"_json;
    cout<<setw(4)<<j<<endl;
    return 0;
}

  或者,直接使用原始字符串的方式:

1
2
3
4
5
6
j = R"(
  {
    "happy": true,
    "pi": 3.141
  }
)"_json;

 或者使用json::parse:

1
j=json::parse("{ \"happy\": true, \"pi\": 3.141 }");

  都将显示:

1
2
3
4
5
Json test
{
    "happy": true,
    "pi": 3.141
}

  

获取对象的字符串

  需要提取其中的字符串时,使用j.dump()即可,如果提供一个整型参数,还可以缩进,例如一般我们用四个字符的话,就可以用j.dump(4),所以上面的例子中,不使用setw的话,可以这样写:

1
cout<<j.dump(4)<<endl;

  另外一个方法是使用j..get<std::string>()方法,get获取的是原始字符串,而dump则是获取的序列化(serialized )的字符串值。

流操作

以文件流为例,读文件创建json对象:

1
2
ifstream i("xdfile.json");
i >> j;

  至于写文件,和写标准输出流没什么差别,前面的火线入门已经展示过。

 

posted @   castor_xu  阅读(6376)  评论(0编辑  收藏  举报
编辑推荐:
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示