github傳送門為:https://nlohmann.github.io/json/
簡介
首先這個庫不是奔着性能去的,設計者考慮的是:直觀的語法(Intuitive syntax)、微小的整合(Trivial integration)、認真的測試(Serious testing)
至於內存效率和速度,反倒不是優先考慮的。
先說說微小的整合。在項目中只需要包含一個json.hpp的單個頭文件就可以了,為了便於編程,使用命名空間會更加方便:
#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對鍵進行了排序,應該是使用了map的緣故。
從字符串到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;
至於寫文件,和寫標准輸出流沒什么差別,前面的火線入門已經展示過。
