Linux系統(tǒng)下如何使用C++解析json文件詳解
1. 背景
工作需要,下班回來自己造輪子,記錄以后查閱。
JSON(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式,和xml類似,本文主要Linux下使用Jsoncpp解析json的方法做一下記錄。
2. 關(guān)于jsoncpp庫的使用簡介
使用jsoncpp有兩種方法
方法一:使用Jsoncpp生成的lib文件
解壓上面下載的Jsoncpp文件,在jsoncpp默認(rèn)生成靜態(tài)鏈接庫。 在工程中引用,只需要包含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,否則編譯會出現(xiàn)錯(cuò)誤。
我上面的都是采用第一種方法
jsoncpp 使用詳解
jsoncpp 主要包含三種類型的 class:Value、Reader、Writer。jsoncpp 中所有對象、類名都在 namespace Json 中,包含 json.h 即可。
Json::Value 只能處理 ANSI 類型的字符串,如果 C++ 程序是用 Unicode 編碼的,最好加一個(gè) Adapt 類來適配。
3. linux下jsoncpp環(huán)境配置
3.1 jsoncpp源碼下載
直接在github搜索jsoncpp即可。給出下載連接:https://github.com/open-source-parsers/jsoncpp
3.2 具體配置步驟
1> 解壓源碼
2> 在源碼目錄的上一層新建build目錄,用來保存編譯過程生成的中間文件
3> 在build目錄執(zhí)行cmake ..
4> 在build目錄執(zhí)行make
5> 在build目錄下執(zhí)行make install
查看安裝在本地的jsoncpp庫
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++寫入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文件,并且寫入成功

要注意的是:
1.如果要寫入的文件不存在,會自動創(chuàng)建該文件;
2.如果文件存在,寫入過程不會覆蓋文件中原有數(shù)據(jù),而是將新數(shù)據(jù)寫在原有數(shù)據(jù)后面。
6. 從字符串解析json
在實(shí)際項(xiàng)目中更多使用的是從文件解析json,從字符串解析json示例只是為了完整記錄。
6.1 簡單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://www.dhdzp.com/article/214039.htm
http://www.dhdzp.com/article/214051.htm
總結(jié)
到此這篇關(guān)于Linux系統(tǒng)下如何使用C++解析json文件的文章就介紹到這了,更多相關(guān)Linux C++解析json文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++11/14 線程調(diào)用類對象和線程傳參的方法
這篇文章主要介紹了C++11/14 線程調(diào)用類對象和線程傳參的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-01-01
C語言使用scanf連續(xù)輸入字符串出現(xiàn)的問題
這篇文章主要介紹了C語言使用scanf連續(xù)輸入字符串出現(xiàn)的問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12
Matlab實(shí)現(xiàn)繪制有氣泡感的網(wǎng)絡(luò)圖
這篇文章主要介紹了如何利用Matlab實(shí)現(xiàn)繪制有氣泡感的網(wǎng)絡(luò)圖,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)Matlab有一定的幫助,需要的可以參考一下2023-02-02
解析c++ 中智能指針引用計(jì)數(shù)為什么不是0原理
這篇文章主要為大家介紹了C語言中智能指針引用計(jì)數(shù)為什么不是0原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08

