簡單好用的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;

  至於寫文件,和寫標準輸出流沒什麼差異,前面的火線入門已經展現過。

相關文章
相關標籤/搜索