C/C++讀寫JSON數(shù)據(jù)的詳細(xì)過程記錄
前言
在進(jìn)行配置文件讀取或者進(jìn)行RPC(Remote Produce Call),我們需要在兩個進(jìn)程間傳遞大量的數(shù)據(jù),這時我們一般會選擇json/xml/protobuf來序列化數(shù)據(jù),加快數(shù)據(jù)的傳輸與解析速度。
JSON(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式。JSON采用完全獨立于語言的文本格式,這些特性使JSON成為理想的數(shù)據(jù)交換語言。易于人閱讀和編寫,同時也易于機(jī)器解析和生成。關(guān)于json數(shù)據(jù)格式的具體介紹,大家可以自己去搜索,今天主要介紹下C/C++如何借助第三方庫來解析json,進(jìn)而實現(xiàn)對json的讀寫。
第三方庫
C/C++本身沒有實現(xiàn)字符串到j(luò)son數(shù)據(jù)或者json數(shù)據(jù)到字符串的轉(zhuǎn)換,所以我們需要借助外部的第三方庫來實現(xiàn)這個功能,jsoncpp是一個由CPP實現(xiàn)的json數(shù)據(jù)解析庫,通過這個靜態(tài)庫我們可以實現(xiàn)字符串到j(luò)son,json到字符串,以及讀寫json文件的功能。
1.下載 jsoncpp github源碼下載地址,目前已經(jīng)release了63個版本,可以選擇一個比較新的版本下載source code.
2.編譯安裝
在linux平臺上的編譯過程如下:
# 安裝cmkae sudo apt-get install cmake #在源碼目錄下創(chuàng)建指定目錄 cd jsoncpp-1.9.5/ mkdir -p build/debug cd build/debug cmake -DCMAKE_BUILD_TYPE=debug -DBUILD_STATIC_LIBS=ON -DBUILD_SHARED_LIBS=OFF -DARCHIVE_INSTALL_DIR=. -G "Unix Makefiles" ../.. make
編譯生成的靜態(tài)庫libjsoncpp.a在 jsoncpp-1.9.5/build/debug/lib目錄下。 執(zhí)行上述命令即可完成編譯,詳細(xì)說明可以點擊 此處查看
3.鏈接
生成的libjsoncpp.a需要我們通過編譯命令鏈接到target中,同時指定頭文件搜索目錄,jsoncpp的頭文件保存在jsoncpp-1.9.5/include/json/include下,通常我們只用到json.h
可以通過以下命令鏈接
g++ -o xxx xxx.cpp -I頭文件搜索路徑 -L庫搜索路徑 -l庫名稱
如果是使用xmake構(gòu)建項目,則只需要在對應(yīng)的target下面添加頭文件路徑,庫路徑,庫名稱,如下
add_includedirs("header search path") add_linkdirs("lib search path") add_links("static/dynamic library name")
在我們的代碼中,需要添加jsoncpp的頭文件json.h
jsoncpp基礎(chǔ)用法
在上述工作完成后,就可以在代碼中使用jsoncpp來完成對json的各種操作,下面我們來看下該庫對json的基本操作
1.從字符串中讀取json
1.1 簡單json數(shù)據(jù) (單層數(shù)據(jù))定義一個字符串來存儲json數(shù)據(jù)
{ "name" : "DeRozan", "age" : "27", "sex" : "man" }
使用json數(shù)據(jù)庫讀取字符串到j(luò)son對象
void readStrJson() { const char* str = "{\"name\":\"DeRozan\",\"age\":21,\"sex\":\"man\"}"; Json::Reader reader; Json::Value root; //從字符串中讀取數(shù)據(jù) if (reader.parse(str, root)) { string name = root["name"].asString(); int age = root["age"].asInt(); string sex = root["sex"].asString(); cout << name + "," << age << "," << sex << endl; } }
程序輸出
DeRozan,21,man
1.2 嵌套json數(shù)據(jù)
json中包含多層嵌套數(shù)據(jù)
{ "name":"Derozan", "major":[ { "Player":"LPL player" }, { "Player":"Basketball Player" }] }
使用jsoncpp讀取多級json數(shù)據(jù)
void readStrProJson() { string strValue = "{\"name\":\"Derozan\",\"major\":[{\"LPL\":\"EDG player\"},{\"NBA\":\"Basketball Player\"}]}"; Json::Reader reader; Json::Value value; if (reader.parse(strValue, value)) { string out = value["name"].asString(); cout << out << endl; const Json::Value arrayObj = value["major"]; for (unsigned int i = 0; i < arrayObj.size(); i++) { out = arrayObj[i]["Player"].asString(); cout << out<<endl; } } }
程序輸出
DeRozan
LPL player
Basketball Player
2.從文件中讀取json
test.json
{ "age" : 25, "friends" : { "friend_age" : 25, "friend_name" : "Derozan", "friend_sex" : "man" }, "hobby" : [ "basket", "women", "sleep" ], "name" : "Alen", "sex" : "women" }
#include <fstream> void readFromFile() { Json::Reader reader; Json::Value root; const char* path = "/home/dexu_tian/Tmp/test.json"; std::ifstream infile(path); if(reader.parse(infile, root)) { //讀取根節(jié)點信息 std::string name = root["name"].asString(); int age = root["age"].asInt(); std::string sex = root["sex"].asString(); std::cout << "My name is " << name << std::endl; std::cout << "I'm " << age << " years old" << std::endl; std::cout << "I'm a " << sex << std::endl; //讀取子節(jié)點信息 std::string friend_name = root["friends"]["friend_name"].asString(); int friend_age = root["friends"]["friend_age"].asInt(); std::string friend_sex = root["friends"]["friend_sex"].asString(); std::cout << "friend's name is " << friend_name << std::endl; std::cout << "friend's sex is "<<friend_sex << std::endl; std::cout << "friend is " << friend_age << " years old" << std::endl; //讀取數(shù)組信息 std::cout << "my hobby:" << std::endl; for (unsigned int i = 0; i < root["hobby"].size(); i++) { std::string ach = root["hobby"][i].asString(); std::cout << ach << '\t'; } std::cout << std::endl; std::cout << "Reading Success!" << std::endl; } }
控制臺輸出
My name is Alen
I'm 25 years old
I'm a women
friend's name is Derozan
friend's sex is man
friend is 25 years old
my hobby:
basket women sleep
Reading Success!
3.寫入json文件
準(zhǔn)備寫入的json內(nèi)容
{ "age" : 27, "friends" : { "friend_age" : 35, "friend_name" : "Alen", "friend_sex" : "man" }, "hobby" : [ "Basketball", "Swimming", "game" ], "name" : "Derozan", "sex" : "man" }
代碼
void writeFileJson() { //根節(jié)點 Json::Value root; //根節(jié)點屬性 root["name"] = Json::Value("Derozan"); root["age"] = Json::Value(27); root["sex"] = Json::Value("man"); //子節(jié)點 Json::Value friends; //子節(jié)點屬性 friends["friend_name"] = Json::Value("Alen"); friends["friend_age"] = Json::Value(35); friends["friend_sex"] = Json::Value("man"); //子節(jié)點掛到根節(jié)點上 root["friends"] = Json::Value(friends); //數(shù)組形式 root["hobby"].append("Basketball"); root["hobby"].append("Swimming"); root["hobby"].append("game"); //直接輸出 //cout << "FastWriter:" << endl; //Json::FastWriter fw; //cout << fw.write(root) << endl << endl; //縮進(jìn)輸出 std::cout << "StyledWriter:" << std::endl; Json::StyledWriter sw; std::cout << sw.write(root) << std::endl << std::endl; //輸出到文件 std::ofstream os; const char* path = "/home/dexu_tian/Tmp/testwrite.json"; os.open(path, std::ios::out | std::ios::app); if (!os.is_open()) std::cout << "error:can not find or create the file which named \" demo.json\"." << std::endl; os << sw.write(root); os.close(); } //本來代碼來源于: https://blog.csdn.net/shuiyixin/article/details/89330529
查看寫入的文件
dexu_tian@VM-4-10-ubuntu:~/Tmp$ cat testwrite.json { "age" : 27, "friends" : { "friend_age" : 35, "friend_name" : "Alen", "friend_sex" : "man" }, "hobby" : [ "Basketball", "Swimming", "game" ], "name" : "Derozan", "sex" : "man" }
總結(jié)
到此這篇關(guān)于C/C++讀寫JSON數(shù)據(jù)的文章就介紹到這了,更多相關(guān)C/C++讀寫JSON數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Qt使用SQLite數(shù)據(jù)庫實現(xiàn)數(shù)據(jù)增刪改查
這篇文章主要為大家詳細(xì)介紹了Qt如何使用SQLite數(shù)據(jù)庫實現(xiàn)數(shù)據(jù)增刪改查功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下2023-06-06C++開發(fā)之PugiXML庫基礎(chǔ)用法示例詳解
PugiXML庫是一個功能強大、簡單易用的C++ XML解析庫,它提供了一組方便的函數(shù)來解析、創(chuàng)建和修改XML文檔,本文介紹了如何使用PugiXML庫來解析、創(chuàng)建和修改XML文檔,以及如何處理錯誤和異常,感興趣的朋友跟隨小編一起看看吧2024-03-03