【C++】JSON for Modern C++

JSON(JavaScript Object Notation)格式作為一種數(shù)據(jù)格式,從最初作為JS語(yǔ)言的子集,以其易于閱讀和處理的優(yōu)勢(shì),逐漸被多種語(yǔ)言所支持,如Python/Java等,均提供了處理JSON格式文本的標(biāo)準(zhǔn)庫(kù)/第三方庫(kù),因而脫離了某種編程語(yǔ)言的標(biāo)簽,成為一種通用的數(shù)據(jù)傳輸格式。

C++也出現(xiàn)了很多的開(kāi)源庫(kù)以支持JSON格式文本的處理,其特點(diǎn)各異,本文主要介紹其中一個(gè)—— Nlohmann JSON。

Nlohmann JSON庫(kù)以C++11實(shí)現(xiàn),主要設(shè)計(jì)目標(biāo)為易用性,體現(xiàn)在該庫(kù)可以通過(guò)一個(gè)頭文件集成到任意項(xiàng)目,并且像STL容器一樣操作JSON對(duì)象。但是并沒(méi)有把內(nèi)存消耗和運(yùn)行速度作為重要的指標(biāo),因此在性能上可能不及一些以性能為主要設(shè)計(jì)目標(biāo)的JSON庫(kù),如果對(duì)C++實(shí)現(xiàn)的各類(lèi)JSON庫(kù)運(yùn)行性能對(duì)比感興趣可以看這里。

先上開(kāi)源庫(kù)地址: https://github.com/nlohmann/json,本文的主要參考資料就是該庫(kù)的README,下面的例子中使用的庫(kù)版本為3.10.2。

一、集成

為支持單文件引入,每次Release版本中都會(huì)有一個(gè)json.hpp,只要下載并把它添加到項(xiàng)目中,然后在要處理JSON的文件中添加如下,并在編譯時(shí)支持C++11(-std=c++11)就可以使用了。

#include "json.hpp" // 替換成放該json.hpp的路徑

// 方便引用
using json = nlohmann::json;

二、使用

本節(jié)主要介紹此JSON庫(kù)四種常用的對(duì)象構(gòu)造方法和一種操作方法

1. 從零構(gòu)造一個(gè)JSON對(duì)象

作為JSON庫(kù)最最基礎(chǔ)的用法,假設(shè)要?jiǎng)?chuàng)建一個(gè)這樣的JSON對(duì)象:

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

使用這個(gè)庫(kù),可以這樣寫(xiě):

// 先創(chuàng)建一個(gè)空J(rèn)SON結(jié)構(gòu)(null)
json j;

// 然后添加一個(gè)Number值,在C++中被存儲(chǔ)為double,j被隱式轉(zhuǎn)換為object結(jié)構(gòu)
j["pi"] = 3.141;

// 添加一個(gè)Boolean值,在C++中被存儲(chǔ)為bool
j["happy"] = true;

// 添加一個(gè)String值,在C++中被存儲(chǔ)為std::string
j["name"] = "Niels";

// 添加一個(gè)null對(duì)象,在C++中被存儲(chǔ)為nullptr
j["nothing"] = nullptr;

// 在Object中添加Object
j["answer"]["everything"] = 42;

// 添加一個(gè)Array對(duì)象,在C++中被存儲(chǔ)為std:vector(使用初始化列表)
j["list"] = { 1, 0, 2 };

// 添加一個(gè)Object,使用一對(duì)初始化列表
j["object"] = { {"currency", "USD"}, {"value", 42.99} };

// 也可以使用下面這種方法定義和上述相同結(jié)構(gòu)的JSON對(duì)象
// 但個(gè)人不太推薦,花括號(hào)多到數(shù)組和對(duì)象很容易混
json j2 = {
  {"pi", 3.141},
  {"happy", true},
  {"name", "Niels"},
  {"nothing", nullptr},
  {"answer", {
    {"everything", 42}
  }},
  {"list", {1, 0, 2}},
  {"object", {
    {"currency", "USD"},
    {"value", 42.99}
  }}
};

2. 由字符串序列化

創(chuàng)建和解析JSON字符串是一種常見(jiàn)的操作。

可以通過(guò)在字符串后面添加_json創(chuàng)建JSON對(duì)象。(由C++11 用戶定義字面量 特性支持)

// 通過(guò)字符串構(gòu)造JSON對(duì)象
json j = "{ \"happy\": true, \"pi\": 3.141 }"_json;

// 或者使用原生字符串構(gòu)造
auto j2 = R"(
  {
    "happy": true,
    "pi": 3.141
  }
)"_json;

// 也可以顯式通過(guò)json::parse解析字符串
auto j3 = json::parse(R"({"happy": true, "pi": 3.141})");

相反的,可以通過(guò).dump()方法將JSON對(duì)象轉(zhuǎn)換成字符串

// 顯式轉(zhuǎn)換為字符串
std::string s = j.dump();    // {"happy":true,"pi":3.141}

// 向dump傳入間隔的空格數(shù),以打印格式易于閱讀的字符串
std::cout << j.dump(4) << std::endl;
// {
//     "happy": true,
//     "pi": 3.141
// }

3. 像STL一樣操作

為了使C++開(kāi)發(fā)者易于上手,該庫(kù)對(duì)JSON對(duì)象的操作模擬了常見(jiàn)的STL容器操作。

// 使用push_back創(chuàng)建Array
json j;
j.push_back("foo");
j.push_back(1);
j.push_back(true);

// 也可以使用C++11標(biāo)準(zhǔn)中的emplace_back
j.emplace_back(1.78);

// 通過(guò)iterator遍歷這個(gè)Array
for (json::iterator it = j.begin(); it != j.end(); ++it) {
  std::cout << *it << '\n';
}

// 或者C++11中的范圍for
for (auto& element : j) {
  std::cout << element << '\n';
}

// getter/setter
const auto tmp = j[0].get<std::string>();   // .get<T>() 顯式轉(zhuǎn)換獲取值
bool foo = j.at(2); // .at(X) 隱式轉(zhuǎn)換獲取值,不過(guò)盡量避免使用隱式轉(zhuǎn)換
j[1] = 42;

// 比較
j == R"(["foo", 1, true, 1.78])"_json;  // true

// 其他方法
j.size();     // 4
j.empty();    // false
j.type();     // json::value_t::array
j.clear();

// 類(lèi)型檢查的一些方法
j.is_null();
j.is_boolean();
j.is_number();
j.is_object();
j.is_array();
j.is_string();

// 查找
if (j.contains("foo")) {
    // JSON對(duì)象中有鍵名foo
}

// 或者通過(guò)iterator來(lái)查找
if (j.find("foo") != j.end()) {
    // JSON對(duì)象中有鍵名foo
}

// 或者用更簡(jiǎn)單的count()
int foo_present = j.count("foo"); // 1
int fob_present = j.count("fob"); // 0

// 刪除
j.erase("foo");

4. 由STL容器構(gòu)造

JSON對(duì)象可以由STL容器直接構(gòu)造,但是由關(guān)聯(lián)容器構(gòu)造的JSON對(duì)象中鍵的順序,由容器中元素的排序順序決定。

#include "json.hpp" // 替換成放該json.hpp的路徑
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <unordered_set>

// 方便引用
using json = nlohmann::json;

int main()
{
    std::vector<int> c_vector {1, 2, 3, 4};
    json j_vec(c_vector);   // [1, 2, 3, 4]

    std::deque<double> c_deque {1.2, 2.3, 3.4, 5.6};
    json j_deque(c_deque);  // [1.2, 2.3, 3.4, 5.6]

    std::list<bool> c_list {true, true, false, true};
    json j_list(c_list);    // [true, true, false, true]

    std::forward_list<int64_t> c_flist {12345678909876, 23456789098765, 34567890987654, 45678909876543};
    json j_flist(c_flist);  // [12345678909876, 23456789098765, 34567890987654, 45678909876543]

    std::array<unsigned long, 4> c_array {{1, 2, 3, 4}};
    json j_array(c_array);  // [1, 2, 3, 4]

    std::set<std::string> c_set {"one", "two", "three", "four", "one"};
    json j_set(c_set);      // ["four", "one", "three", "two"]

    std::unordered_set<std::string> c_uset {"one", "two", "three", "four", "one"};
    json j_uset(c_uset);    // maybe ["two", "three", "four", "one"]

    std::multiset<std::string> c_mset {"one", "two", "one", "four"};
    json j_mset(c_mset);    // maybe ["one", "two", "one", "four"]

    std::unordered_multiset<std::string> c_umset {"one", "two", "one", "four"};
    json j_umset(c_umset);  // maybe ["one", "two", "one", "four"]


    return 0;
}

同樣的,對(duì)于有鍵值對(duì)的關(guān)聯(lián)容器,其鍵要能構(gòu)造成std::string,它才能直接構(gòu)造為JSON對(duì)象。

std::map<std::string, int> c_map { {"one", 1}, {"two", 2}, {"three", 3} };
json j_map(c_map);      // {"one": 1, "three": 3, "two": 2 }

std::unordered_map<const char*, double> c_umap { {"one", 1.2}, {"two", 2.3}, {"three", 3.4} };
json j_umap(c_umap);    // {"one": 1.2, "two": 2.3, "three": 3.4}

std::multimap<std::string, bool> c_mmap { {"one", true}, {"two", true}, {"three", false}, {"three", true} };
json j_mmap(c_mmap);    // maybe {"one": true, "two": true, "three": true}

std::unordered_multimap<std::string, bool> c_ummap { {"one", true}, {"two", true}, {"three", false}, {"three", true} };
json j_ummap(c_ummap);  // maybe {"one": true, "two": true, "three": true}

5. 由自定義類(lèi)型構(gòu)造

除了STL容器,由自定義類(lèi)型的對(duì)象構(gòu)造JSON對(duì)象也是比較常用的操作。

當(dāng)然,可以通過(guò)手動(dòng)一個(gè)個(gè)拷貝鍵值對(duì)來(lái)完成,如下

// 一個(gè)簡(jiǎn)單的自定義結(jié)構(gòu)
struct person {
    std::string name;
    std::string address;
    int age;
};

person p = {"Ned Flanders", "744 Evergreen Terrace", 60};

// person轉(zhuǎn)換成JSON: 把自定義對(duì)象中的每個(gè)值都拷貝給JSON對(duì)象
json j;
j["name"] = p.name;
j["address"] = p.address;
j["age"] = p.age;

// ...

// 由JSON轉(zhuǎn)成person: 把JSON對(duì)象中的每個(gè)值拷貝給自定義類(lèi)型
person p {
    j["name"].get<std::string>(),
    j["address"].get<std::string>(),
    j["age"].get<int>()
};

這樣確實(shí)可行,但實(shí)在談不上易用,所幸該庫(kù)提供了一個(gè)更好的方法:

// 創(chuàng)建person類(lèi)型對(duì)象
person p {"Ned Flanders", "744 Evergreen Terrace", 60};

// person -> json
json j = p;

std::cout << j << std::endl;
// {"address":"744 Evergreen Terrace","age":60,"name":"Ned Flanders"}

// json -> person
auto p2 = j.get<person>();

想要可以這樣轉(zhuǎn)換自定義類(lèi)型,需要提供兩個(gè)方法:

using json = nlohmann::json;

void to_json(json& j, const person& p) {
    j = json{{"name", p.name}, {"address", p.address}, {"age", p.age}};
}

void from_json(const json& j, person& p) {
    j.at("name").get_to(p.name);
    j.at("address").get_to(p.address);
    j.at("age").get_to(p.age);
}

就是這樣,當(dāng)由自定義類(lèi)型person構(gòu)造JSON時(shí),會(huì)調(diào)用上面定義的void to_json(json& j, const person& p)。

相同的,由JSON轉(zhuǎn)成自定義類(lèi)型person時(shí),會(huì)調(diào)用定義的void from_json(const json& j, person& p)。

完整范例代碼如下:

#include <iostream>
#include "json.hpp" // 替換成放json.hpp的路徑

// 方便引用
using json = nlohmann::json;

// 一個(gè)簡(jiǎn)單的自定義結(jié)構(gòu)
struct person {
    std::string name;
    std::string address;
    int age;
};

// person -> json
void to_json(json& j, const person& p) {
    j = json{{"name", p.name}, {"address", p.address}, {"age", p.age}};
}

// json -> person
void from_json(const json& j, person& p) {
    j.at("name").get_to(p.name);
    j.at("address").get_to(p.address);
    j.at("age").get_to(p.age);
}

int main()
{
    person p = {"Ned Flanders", "744 Evergreen Terrace", 60};

    json j = p;

    std::cout << j << std::endl;

    auto p2 = j.get<person>();

    return 0;
}

這種轉(zhuǎn)換方法的優(yōu)點(diǎn)是非侵入式,即無(wú)需修改原結(jié)構(gòu)體的代碼,在新建的文件中聲明轉(zhuǎn)換方法即可。

以上就是Nlohmann JSON庫(kù)的常用用法了,更詳盡的介紹可以詳見(jiàn)README或者json.nlohmann.me。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容