wordpress 企業(yè) 模板 下載windows優(yōu)化大師卸載
目錄
引言
一.JSON簡(jiǎn)介
二. Jsoncpp庫(kù)概述
三. Jsoncpp核心類(lèi)介紹
3.1 Json::Value類(lèi)
3.2 序列化與反序列化類(lèi)
四. 實(shí)現(xiàn)序列化
五. 實(shí)現(xiàn)反序列化
結(jié)語(yǔ)
引言
在現(xiàn)代軟件開(kāi)發(fā)中,數(shù)據(jù)交換格式扮演著至關(guān)重要的角色。JSON(JavaScript Object Notation)以其簡(jiǎn)潔、易于閱讀和支持多種數(shù)據(jù)類(lèi)型的特點(diǎn),成為了數(shù)據(jù)交換領(lǐng)域的明星。本文將深入探討JSON的基本概念、數(shù)據(jù)類(lèi)型以及如何使用Jsoncpp庫(kù)實(shí)現(xiàn)JSON的序列化與反序列化。
一.JSON簡(jiǎn)介
JSON是一種輕量級(jí)的數(shù)據(jù)交換格式,它基于文本,易于人閱讀和編寫(xiě),同時(shí)也易于機(jī)器解析和生成。JSON的數(shù)據(jù)結(jié)構(gòu)包括以下幾種:
- 對(duì)象:由花括號(hào)
{}
包圍,存儲(chǔ)鍵值對(duì)。- 數(shù)組:由中括號(hào)
[]
包圍,存儲(chǔ)有序集合。- 字符串:由雙引號(hào)
""
包圍。- 數(shù)字:整數(shù)或浮點(diǎn)數(shù)。
- 布爾值:
true
或false
。- null:表示空值。
例:?明同學(xué)的學(xué)?信息
char name = "?明";
int age = 18;
float score[3] = {88.5, 99, 58};
則json這種數(shù)據(jù)交換格式是將這多種數(shù)據(jù)對(duì)象組織成為?個(gè)字符串:
[{"姓名" : "?明","年齡" : 18,"成績(jī)" : [88.5, 99, 58]},{"姓名" : "??","年齡" : 18,"成績(jī)" : [88.5, 99, 58]}
]
二. Jsoncpp庫(kù)概述
Jsoncpp是一個(gè)流行的C++庫(kù),用于處理JSON數(shù)據(jù)。它提供了序列化和反序列化的機(jī)制,使得在C++程序中生成和解析JSON數(shù)據(jù)變得簡(jiǎn)單。
三. Jsoncpp核心類(lèi)介紹
// Json數(shù)據(jù)對(duì)象類(lèi)
class Json::Value
{Value &operator=(const Value &other); // Value重載了[]和=,因此所有的賦值和獲取數(shù)據(jù)都可以通過(guò)Value &operator[](const std::string &key); // 簡(jiǎn)單的?式完成 val["姓名"] = "?明 ";Value &operator[](const char *key);Value removeMember(const char *key); // 移除元素const Value &operator[](ArrayIndex index) const; // val["成績(jī)"][0]Value &append(const Value &value); // 添加數(shù)組元素val["績(jī)"].append(88);ArrayIndex size() const; // 獲取數(shù)組元素個(gè)數(shù) val["績(jī)"].size();std::string asString() const; // 轉(zhuǎn)string string name =val["name"].asString();const char *asCString() const; // 轉(zhuǎn)char* char *name =val["name"].asCString();Int asInt() const; // 轉(zhuǎn)int int age = val["age"].asInt();float asFloat() const; // 轉(zhuǎn)floatbool asBool() const; // 轉(zhuǎn) bool
};
// json序列化類(lèi),低版本?這個(gè)更簡(jiǎn)單
class JSON_API Writer
{virtual std::string write(const Value &root) = 0;
}
class JSON_API FastWriter : public Writer
{virtual std::string write(const Value &root);
}
class JSON_API StyledWriter : public Writer
{virtual std::string write(const Value &root);
}
// json序列化類(lèi),?版本推薦,如果?低版本的接?可能會(huì)有警告
class JSON_API StreamWriter
{virtual int write(Value const &root, std::ostream *sout) = 0;
}
class JSON_API StreamWriterBuilder : public StreamWriter::Factory
{virtual StreamWriter *newStreamWriter() const;
}
// json反序列化類(lèi),低版本?起來(lái)更簡(jiǎn)單
class JSON_API Reader
{bool parse(const std::string &document, Value &root, bool collectComments = true);
}
// json反序列化類(lèi),?版本更推薦
class JSON_API CharReader
{virtual bool parse(char const *beginDoc, char const *endDoc,Value *root, std::string *errs) = 0;
}
class JSON_API CharReaderBuilder : public CharReader::Factory
{virtual CharReader *newCharReader() const;
}
3.1 Json::Value類(lèi)
Json::Value
類(lèi)是Jsoncpp中表示JSON數(shù)據(jù)的核心類(lèi)。它提供了一系列的方法來(lái)操作JSON數(shù)據(jù):
operator[]
:通過(guò)鍵名或數(shù)組索引訪問(wèn)數(shù)據(jù)。asString
、asInt
、asFloat
、asBool
:將JSON數(shù)據(jù)轉(zhuǎn)換為相應(yīng)的C++數(shù)據(jù)類(lèi)型。append
:向JSON數(shù)組中添加元素。
3.2 序列化與反序列化類(lèi)
序列化是將JSON對(duì)象轉(zhuǎn)換為字符串的過(guò)程,反序列化則是相反的過(guò)程。Jsoncpp提供了以下類(lèi)來(lái)實(shí)現(xiàn)這些功能:
StreamWriter
和StreamWriterBuilder
:用于創(chuàng)建序列化器,將Json::Value
對(duì)象轉(zhuǎn)換為JSON格式的字符串。CharReader
和CharReaderBuilder
:用于創(chuàng)建反序列化器,將JSON格式的字符串解析為Json::Value
對(duì)象。
四. 實(shí)現(xiàn)序列化
下面是一個(gè)使用Jsoncpp實(shí)現(xiàn)序列化的示例:
#include <jsoncpp/json/json.h>
#include <iostream>
#include <sstream>
#include <memory>int main() {const char* name = "小明";int age = 19;float score[] = {77.5, 88, 99.5};Json::Value val;val["姓名"] = name;val["年齡"] = age;val["成績(jī)"] = Json::Value(Json::arrayValue);for (float s : score) {val["成績(jī)"].append(s);}Json::StreamWriterBuilder swb;std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());std::stringstream ss;// 檢查sw是否為空指針if (!sw) {std::cerr << "Failed to create StreamWriter" << std::endl;return -1;}try {int result = sw->write(val, &ss);if (result != 0) { // 檢查是否有錯(cuò)誤std::cerr << "Write failed with error code: " << result << std::endl;} else {std::cout << ss.str() << std::endl;}} catch (const std::exception& e) {std::cerr << "Exception occurred: " << e.what() << std::endl;return -1;}return 0;
}
五. 實(shí)現(xiàn)反序列化
下面是一個(gè)使用Jsoncpp實(shí)現(xiàn)反序列化的示例:
#include <jsoncpp/json/json.h>
#include <iostream>
#include <string>int main()
{std::string str = R"({"姓名":"小明", "年齡":18, "成績(jī)":[76.5, 55, 88]})";Json::Value root;Json::CharReaderBuilder crb;std::unique_ptr<Json::CharReader> cr(crb.newCharReader());std::string err;if (!cr->parse(str.c_str(), str.c_str() + str.size(), &root, &err)){std::cout << "Parse error: " << err << std::endl;}else{std::cout << "Name: " << root["姓名"].asString() << std::endl;std::cout << "Age: " << root["年齡"].asInt() << std::endl;int sz = root["成績(jī)"].size();for (int i = 0; i < sz; i++){std::cout << "Score: " << root["成績(jī)"][i].asFloat() << std::endl;}}return 0;
}
結(jié)語(yǔ)
JSON作為一種靈活的數(shù)據(jù)交換格式,結(jié)合Jsoncpp庫(kù),為C++開(kāi)發(fā)者提供了強(qiáng)大的數(shù)據(jù)交換能力。無(wú)論是網(wǎng)絡(luò)通信還是數(shù)據(jù)存儲(chǔ),JSON和Jsoncpp都是你的理想選擇。通過(guò)本文的介紹,希望你能對(duì)JSON和Jsoncpp有一個(gè)全面的了解,并能將其應(yīng)用到實(shí)際開(kāi)發(fā)中。