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

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

简介java

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

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

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

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

  

火线入门编程

#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

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

  

从字符串到Json对象性能

经过字符串解析:测试

 一种方式是使用_json:

#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;
}

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

j = R"(
  {
    "happy": true,
    "pi": 3.141
  }
)"_json;

 或者使用json::parse:

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

  都将显示:

Json test
{
    "happy": true,
    "pi": 3.141
}

  

获取对象的字符串

  须要提取其中的字符串时,使用j.dump()便可,若是提供一个整型参数,还能够缩进,例如通常咱们用四个字符的话,就能够用j.dump(4),因此上面的例子中,不使用setw的话,能够这样写:

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

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

流操做

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

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

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