Linux系統(tǒng)下如何使用C++解析json文件詳解
1. 背景
工作需要,下班回來(lái)自己造輪子,記錄以后查閱。
JSON(JavaScript Object Notation) 是一種輕量級(jí)的數(shù)據(jù)交換格式,和xml類(lèi)似,本文主要Linux下使用Jsoncpp解析json的方法做一下記錄。
2. 關(guān)于jsoncpp庫(kù)的使用簡(jiǎn)介
使用jsoncpp有兩種方法
方法一:使用Jsoncpp生成的lib文件
解壓上面下載的Jsoncpp文件,在jsoncpp默認(rèn)生成靜態(tài)鏈接庫(kù)。 在工程中引用,只需要包含include/json下的頭文件及生成的.lib文件即可。
方法二:使用Jsoncpp包中的.cpp和.h文件
解壓上面下載的Jsoncpp文件,把jsoncpp-src-0.5.0文件拷貝到工程目錄下,將jsoncpp-src-0.5.0\jsoncpp-src-0.5.0\include\json和jsoncpp-src-0.5.0\jsoncpp-src-0.5.0\src\lib_json目錄里的文件包含到VS工程中,在VS工程的屬性C/C++下General中Additional Include Directories包含頭文件目錄.\jsoncpp-src-0.5.0\include。在使用的cpp文件中包含json頭文件即可,如:#include "json/json.h"。將json_reader.cpp、json_value.cpp和json_writer.cpp三個(gè)文件的Precompiled Header屬性設(shè)置為Not Using Precompiled Headers,否則編譯會(huì)出現(xiàn)錯(cuò)誤。
我上面的都是采用第一種方法
jsoncpp 使用詳解
jsoncpp 主要包含三種類(lèi)型的 class:Value、Reader、Writer。jsoncpp 中所有對(duì)象、類(lèi)名都在 namespace Json 中,包含 json.h 即可。
Json::Value 只能處理 ANSI 類(lèi)型的字符串,如果 C++ 程序是用 Unicode 編碼的,最好加一個(gè) Adapt 類(lèi)來(lái)適配。
3. linux下jsoncpp環(huán)境配置
3.1 jsoncpp源碼下載
直接在github搜索jsoncpp即可。給出下載連接:https://github.com/open-source-parsers/jsoncpp
3.2 具體配置步驟
1> 解壓源碼
2> 在源碼目錄的上一層新建build目錄,用來(lái)保存編譯過(guò)程生成的中間文件
3> 在build目錄執(zhí)行cmake ..
4> 在build目錄執(zhí)行make
5> 在build目錄下執(zhí)行make install
查看安裝在本地的jsoncpp庫(kù)
ls /usr/local/include ls/usr/local/lib

4. 使用c++讀取json文件示例
demo.json文件【源碼直接抄錄自https://blog.csdn.net/shuiyixin/article/details/89330529】
{
"age" : 21,
"friends" : {
"friend_age" : 21,
"friend_name" : "ZhaoWuxian",
"friend_sex" : "man"
},
"hobby" : [ "sing", "run", "Tai Chi" ],
"name" : "shuiyixin",
"sex" : "man"
}
test.cpp文件
#include <iostream>
#include <json/json.h>
#include <fstream>
using namespace std;
void readFileJson()
{
Json::Reader reader;
Json::Value root;
//從文件中讀取,保證當(dāng)前文件有demo.json文件
ifstream in("demo.json", ios::binary);
if (!in.is_open())
{
cout << "Error opening file\n";
return;
}
if (reader.parse(in, root))
{
//讀取根節(jié)點(diǎn)信息
string name = root["name"].asString();
int age = root["age"].asInt();
string sex = root["sex"].asString();
cout << "My name is " << name << endl;
cout << "I'm " << age << " years old" << endl;
cout << "I'm a " << sex << endl;
//讀取子節(jié)點(diǎn)信息
string friend_name = root["friends"]["friend_name"].asString();
int friend_age = root["friends"]["friend_age"].asInt();
string friend_sex = root["friends"]["friend_sex"].asString();
cout << "My friend's name is " << friend_name << endl;
cout << "My friend's sex is "<<friend_sex << endl;
cout << "My friend is " << friend_age << " years old" << endl;
//讀取數(shù)組信息
cout << "Here's my hobby:" << endl;
for (unsigned int i = 0; i < root["hobby"].size(); i++)
{
string ach = root["hobby"][i].asString();
cout << ach << '\t';
}
cout << endl;
cout << "Reading Complete!" << endl;
}
else
{
cout << "parse error\n" << endl;
}
in.close();
}
int main(void)
{
readFileJson();
return 0;
}
執(zhí)行結(jié)果如下:

5. 使用c++寫(xiě)入json文件示例
test.cpp文件:
#include <iostream>
#include <json/json.h>
#include <fstream>
using namespace std;
void writeFileJson()
{
//根節(jié)點(diǎn)
Json::Value root;
//根節(jié)點(diǎn)屬性
root["name"] = Json::Value("shuiyixin");
root["age"] = Json::Value(21);
root["sex"] = Json::Value("man");
//子節(jié)點(diǎn)
Json::Value friends;
//子節(jié)點(diǎn)屬性
friends["friend_name"] = Json::Value("ZhaoWuxian");
friends["friend_age"] = Json::Value(21);
friends["friend_sex"] = Json::Value("man");
//子節(jié)點(diǎn)掛到根節(jié)點(diǎn)上
root["friends"] = Json::Value(friends);
//數(shù)組形式
root["hobby"].append("sing");
root["hobby"].append("run");
root["hobby"].append("Tai Chi");
//直接輸出
//cout << "FastWriter:" << endl;
//Json::FastWriter fw;
//cout << fw.write(root) << endl << endl;
//縮進(jìn)輸出
cout << "StyledWriter:" << endl;
Json::StyledWriter sw;
cout << sw.write(root) << endl << endl;
//輸出到文件
ofstream os;
os.open("demo.json", std::ios::out | std::ios::app);
if (!os.is_open())
cout << "error:can not find or create the file which named \" demo.json\"." << endl;
os << sw.write(root);
os.close();
}
int main(void)
{
writeFileJson();
return 0;
}
執(zhí)行結(jié)果如下:可以看到已經(jīng)在目錄新建了demo.json文件,并且寫(xiě)入成功

要注意的是:
1.如果要寫(xiě)入的文件不存在,會(huì)自動(dòng)創(chuàng)建該文件;
2.如果文件存在,寫(xiě)入過(guò)程不會(huì)覆蓋文件中原有數(shù)據(jù),而是將新數(shù)據(jù)寫(xiě)在原有數(shù)據(jù)后面。
6. 從字符串解析json
在實(shí)際項(xiàng)目中更多使用的是從文件解析json,從字符串解析json示例只是為了完整記錄。
6.1 簡(jiǎn)單json樣式字符串解析示例
#include <iostream>
#include <json/json.h>
#include <fstream>
using namespace std;
void readStrJson()
{
//字符串
const char* str =
"{\"name\":\"shuiyixin\",\"age\":\"21\",\"sex\":\"man\"}";
// "{
// "name" : "shuiyixin",
// "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["nomen"].asInt();
string sex = root["sex"].asString();
cout << name + "," << age << "," << sex << endl;
}
}
int main(void)
{
readStrJson();
return 0;
}
執(zhí)行結(jié)果如下:

6.2 復(fù)雜json樣式字符串解析示例
#include <iostream>
#include <json/json.h>
#include <fstream>
using namespace std;
void readStrProJson()
{
string strValue = "{\"name\":\"shuiyixin\",\"major\":[{\"AI\":\"MachineLearning\"},{\"AI\":\"DeepLearning\"},{\"AI\":\"ComputerVision\"}]}";
/*
{
"name":"shuiyixin",
"major":[
{
"AI":"MachineLearning"
},
{
"AI":"DeepLearning"
},
{
"AI":"ComputerVision"
}]
}
*/
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]["AI"].asString();
cout << out<<endl;
}
}
}
int main(void)
{
readStrProJson();
return 0;
}
執(zhí)行結(jié)果如下:

參看連接:
http://m.fzitv.net/article/214039.htm
http://m.fzitv.net/article/214051.htm
總結(jié)
到此這篇關(guān)于Linux系統(tǒng)下如何使用C++解析json文件的文章就介紹到這了,更多相關(guān)Linux C++解析json文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++11/14 線程調(diào)用類(lèi)對(duì)象和線程傳參的方法
這篇文章主要介紹了C++11/14 線程調(diào)用類(lèi)對(duì)象和線程傳參的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-01-01
C語(yǔ)言使用scanf連續(xù)輸入字符串出現(xiàn)的問(wèn)題
這篇文章主要介紹了C語(yǔ)言使用scanf連續(xù)輸入字符串出現(xiàn)的問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12
C++中類(lèi)型推斷(auto和decltype)的使用
在C++11之前,每個(gè)數(shù)據(jù)類(lèi)型都需要在編譯時(shí)顯示聲明,在運(yùn)行時(shí)限制表達(dá)式的值,但在C++的新版本之后,引入了 auto 和 decltype等關(guān)鍵字,本文就來(lái)介紹一下C++中類(lèi)型推斷(auto和decltype)的使用,感興趣的可以了解一下2023-12-12
Matlab實(shí)現(xiàn)繪制有氣泡感的網(wǎng)絡(luò)圖
這篇文章主要介紹了如何利用Matlab實(shí)現(xiàn)繪制有氣泡感的網(wǎng)絡(luò)圖,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Matlab有一定的幫助,需要的可以參考一下2023-02-02
C++實(shí)現(xiàn)簡(jiǎn)單的掃雷游戲(控制臺(tái)版)
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)簡(jiǎn)單的掃雷游戲,控制臺(tái)版的掃雷游戲希望大家喜歡,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-05-05
解析c++ 中智能指針引用計(jì)數(shù)為什么不是0原理
這篇文章主要為大家介紹了C語(yǔ)言中智能指針引用計(jì)數(shù)為什么不是0原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08
數(shù)據(jù)結(jié)構(gòu)之紅黑樹(shù)詳解
這篇文章主要介紹了數(shù)據(jù)結(jié)構(gòu)之紅黑樹(shù)詳解,紅黑樹(shù)是一種自平衡二叉查找樹(shù),它的統(tǒng)計(jì)性能要好于平衡二叉樹(shù)(AVL樹(shù)),因此,紅黑樹(shù)在很多地方都有應(yīng)用,需要的朋友可以參考下2014-08-08

