您好,登錄后才能下訂單哦!
在C++中,有多種庫可以用于序列化和處理JSON格式的數(shù)據(jù)
示例代碼:
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main() {
// 創(chuàng)建一個JSON對象
json j = {
{"name", "John"},
{"age", 30},
{"is_student", false}
};
// 將JSON對象轉(zhuǎn)換為字符串
std::string json_str = j.dump();
std::cout << "JSON string: " << json_str << std::endl;
// 從字符串解析JSON對象
json parsed_json = json::parse(json_str);
std::cout << "Parsed name: " << parsed_json["name"] << std::endl;
std::cout << "Parsed age: " << parsed_json["age"] << std::endl;
std::cout << "Parsed is_student: " << parsed_json["is_student"] << std::endl;
return 0;
}
示例代碼:
#include <iostream>
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
using namespace rapidjson;
int main() {
// 創(chuàng)建一個JSON對象
Document d;
d.SetObject();
d.AddMember("name", "John", d.GetAllocator());
d.AddMember("age", 30, d.GetAllocator());
d.AddMember("is_student", false, d.GetAllocator());
// 將JSON對象轉(zhuǎn)換為字符串
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
std::string json_str = buffer.GetString();
std::cout << "JSON string: " << json_str << std::endl;
// 從字符串解析JSON對象
Document parsed_json;
parsed_json.Parse(json_str.c_str());
std::cout << "Parsed name: " << parsed_json["name"].GetString() << std::endl;
std::cout << "Parsed age: " << parsed_json["age"].GetInt() << std::endl;
std::cout << "Parsed is_student: " << (parsed_json["is_student"].GetBool() ? "true" : "false") << std::endl;
return 0;
}
這些庫都提供了詳細(xì)的文檔和示例,可以幫助您快速上手并在項(xiàng)目中使用它們。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。