معالجة JSON في C++: نظرة عامة على المكتبات وأمثلة عملية
JSON (JavaScript Object Notation) هو تنسيق خفيف لتبادل البيانات، يُستخدم على نطاق واسع في تطبيقات الويب وواجهات برمجة التطبيقات (API) وملفات التكوين. في لغة C++، لا يتم تضمين العمل مع JSON في المكتبة القياسية، لذلك يستخدم المطورون مكتبات خارجية. في هذه المقالة، سنستعرض ثلاث أدوات شائعة: nlohmann/json وRapidJSON وBoost.JSON. ستتعلم كيفية تثبيتها، وتحليل JSON، وإنشاء هياكل خاصة بك، وتسلسل البيانات. جميع الأمثلة مصحوبة بكود بلغة C++.
1. مكتبة nlohmann/json
nlohmann/json هي المكتبة الأكثر شيوعًا للعمل مع JSON في C++. تشتهر بتركيبها البسيط والبديهي الذي يشبه Python أو JavaScript. المكتبة هي header-only (ملفات رأس فقط)، مما يبسط التكامل: يكفي نسخ ملف json.hpp إلى المشروع.
التثبيت
قم بتنزيل json.hpp من GitHub وقم بتضمينه:
#include "json.hpp"using json = nlohmann::json;تحليل سلسلة JSON
#include <iostream>#include "json.hpp"
int main() { std::string json_str = R"({ "name": "Alice", "age": 30, "is_student": false, "skills": ["C++", "Python", "JSON"] })";
json data = json::parse(json_str);
std::cout << "Name: " << data["name"] << std::endl; std::cout << "Age: " << data["age"] << std::endl; std::cout << "First skill: " << data["skills"][0] << std::endl;
return 0;}إنشاء JSON وتسلسله
json person;person["name"] = "Bob";person["age"] = 25;person["is_student"] = true;person["languages"].push_back("C");person["languages"].push_back("Java");
std::string serialized = person.dump(4); // 4 — مسافة بادئة لإخراج جميلstd::cout << serialized << std::endl;2. مكتبة RapidJSON
RapidJSON هي مكتبة عالية الأداء، تركز على السرعة والاستخدام الأدنى للذاكرة. وهي أيضًا header-only وتدعم أسلوب التحليل SAX (التدفقي) وأسلوب DOM (بناء شجرة). مناسبة للمشاريع التي تكون فيها الأداء مهمًا، مثل محركات الألعاب أو الخوادم عالية التحميل.
التثبيت
قم بتنزيل الملفات من مستودع RapidJSON وقم بتضمينها:
#include "rapidjson/document.h"#include "rapidjson/writer.h"#include "rapidjson/stringbuffer.h"تحليل JSON
#include <iostream>#include "rapidjson/document.h"
int main() { const char* json = "{\\"name\\":\\"Charlie\\",\\"age\\":28,\\"active\\":true}"; rapidjson::Document doc; doc.Parse(json);
if (doc.HasParseError()) { std::cerr << "Parse error!" << std::endl; return 1; }
std::cout << "Name: " << doc["name"].GetString() << std::endl; std::cout << "Age: " << doc["age"].GetInt() << std::endl;
return 0;}إنشاء JSON وتسلسله
rapidjson::Document doc;doc.SetObject();rapidjson::Document::AllocatorType& allocator = doc.GetAllocator();
doc.AddMember("name", "Diana", allocator);doc.AddMember("score", 95.5, allocator);
rapidjson::StringBuffer buffer;rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);doc.Accept(writer);
std::cout << buffer.GetString() << std::endl;3. مكتبة Boost.JSON
Boost.JSON هي جزء من مكتبات Boost، تم اعتمادها رسميًا في C++ Bo