C++操作.json文件的超詳細(xì)新手教程
1.JSON簡(jiǎn)介
1.1 什么是JSON:
JSON是一種純字符串形式的數(shù)據(jù),它本身不提供任何方法(函數(shù)),非常適合在網(wǎng)絡(luò)中進(jìn)行傳輸。JavaScript、PHP、Java、Python、C++等編程語言都內(nèi)置了處理JSON數(shù)據(jù)的方法。
JSON 是基于 JavaScript(Standard ECMA-262 3rd Edition - December 1999)的一個(gè)子集,是一種開放的、輕量級(jí)的數(shù)據(jù)交換格式,采用獨(dú)立于編程語言的文本格式來存儲(chǔ)和表示數(shù)據(jù),易于程序員閱讀與編寫,同時(shí)也易于計(jì)算機(jī)解析和生成,通常用于在 Web 客戶端(瀏覽器)與 Web 服務(wù)器端之間傳遞數(shù)據(jù)。
在JSON中,使用一下兩種方式表示數(shù)據(jù):
- object(對(duì)象):鍵/值對(duì)(名稱/值)的集合,使用花括號(hào)
{}定義。在每個(gè)鍵/值對(duì)中,以鍵開頭,后跟一個(gè)冒號(hào):,最后是值。多個(gè)鍵/值對(duì)之間使用逗號(hào),分隔,例如"name":"FilterWindow","paramtype":"0"。 - Array(數(shù)組):值的有序集合,使用方括號(hào)
[]定義,數(shù)組中每個(gè)值之間使用逗號(hào),進(jìn)行分隔。
下面展示一個(gè)簡(jiǎn)單的JSON數(shù)據(jù):
{
"name" : "FilterWindow",
"paramtype" : "0",
"range" :
{
"max" : 99,
"min" : 3
},
"required" : true,
"title" : "濾波窗口大小",
"type" : "int",
"value" : 51
"tempValue" :
[
"不生成" : 1,
"生成" : 0
],
}
1.2 JSON的優(yōu)缺點(diǎn):
優(yōu)點(diǎn):
相對(duì)于txt,word來說,json格式更加明確,獲取重要信息非常方便。
相對(duì)于xml來說,json格式更加簡(jiǎn)潔,存儲(chǔ)同樣的文件,花費(fèi)的內(nèi)存更小。
相對(duì)于Excel來說,json更適合存儲(chǔ)字符類文件。Excel相當(dāng)于比較簡(jiǎn)單的數(shù)據(jù)庫了。
相對(duì)于數(shù)據(jù)庫來說,json更加方便,數(shù)據(jù)庫我們還需要做一些設(shè)置,安裝一些軟件。json可以直接使用。
缺點(diǎn):
只有一種數(shù)字類型:JSON中只能支持IEEE-754雙精度浮點(diǎn)格式,因此我們無法使用JSON來存儲(chǔ)許多編程語言中多樣化的數(shù)字類型;
沒有日期類型:在JSON中我們只能通過日期的字符串(例如:1970-01-01)或者時(shí)間戳(例如:1632366361)來表示日期;
沒有注釋:在JSON中無法添加注釋;
冗長:雖然JSON比XML更加簡(jiǎn)潔,但它不是最簡(jiǎn)潔的數(shù)據(jù)交換格式,對(duì)于數(shù)據(jù)量龐大或用途特殊的服務(wù),我們需要更加高效的數(shù)據(jù)格式。
1.3 JSON的存儲(chǔ):
JSON數(shù)據(jù)可以存儲(chǔ)在.json格式的文件中(與.txt格式類似,都屬于純文本文件),也可以將JSON數(shù)據(jù)以字符串的形式存儲(chǔ)在數(shù)據(jù)庫、Cookie、Session中。要使用存儲(chǔ)好的JSON數(shù)據(jù)也非常簡(jiǎn)單,不同的編程語言中提供了不同的方法來檢索和解析JSON數(shù)據(jù),今天我們的重點(diǎn)就是使用C++來操作.json文件。而C++主要使用jsoncpp這個(gè)跨平臺(tái)的開源庫來實(shí)現(xiàn)對(duì).json文件的各類操作。
2.jsoncpp庫介紹
2.1 jsoncpp庫的配置使用:
這里我就不按照網(wǎng)上常規(guī)的方式來介紹了,常規(guī)的方法無非是關(guān)于下載jsoncpp庫,然后使用Windows編譯(vs2015),最后整理出include及l(fā)ib來使用jsoncpp庫。我這里是整理好的,是直接把include里的所有文件集合成json.h以及json.cpp。用的時(shí)候直接把這些文件包含進(jìn)自己的項(xiàng)目一起編譯即可。

2.2 jsoncpp庫內(nèi)部構(gòu)成:
jsoncpp主要包含三個(gè)class(類):Value、Reader、Writer。注意Json::Value只能處理ANSI類型的字符串,如果C++程序是用Unicode編碼的,最好加一個(gè)Adapt類來適配。
Value: 是jsoncpp中最基本、最重要的類,用于表示各種類型的對(duì)象,jsoncpp支持的對(duì)象類型可見下面的Json::ValueType枚舉值;Value類的對(duì)象代表一個(gè)JSON,既可以代表一個(gè)文檔,也可以代表文檔中一個(gè)值。如同JSON中定義的“值”一樣,Value是遞歸的。
enum ValueType
{
nullValue = 0, ///< 'null' value
intValue, ///< signed integer value
uintValue, ///< unsigned integer value
realValue, ///< double value
stringValue, ///< UTF-8 string value
booleanValue, ///< bool value
arrayValue, ///< array value (ordered list)
objectValue ///< object value (collection of name/value pairs).
};
Value類里的函數(shù)如下所示:
1、【構(gòu)造函數(shù)】 Value( ValueType type = nullValue ); Value( Int value ); Value( UInt value ); Value( double value ); Value( const char *value ); Value( const char *beginValue, const char *endValue ); 2、【拷貝構(gòu)造函數(shù)】 Value( const StaticString &value ); Value( const std::string &value ); Value( const Value &other ); 3、【相同類型的比較、交換、類型的獲取】 void swap( Value &other ); ValueType type() const; int compare( const Value &other ); 4、【相應(yīng)的賦值運(yùn)算符的重載函數(shù)】 Value &operator=( const Value &other ); bool operator <( const Value &other ) const; bool operator <=( const Value &other ) const; bool operator >=( const Value &other ) const; bool operator >( const Value &other ) const; bool operator ==( const Value &other ) const; bool operator !=( const Value &other ) const; bool operator!() const; Value &operator[]( UInt index ); const Value &operator[]( UInt index ) const; 5、【將Value對(duì)象進(jìn)行相應(yīng)的類型轉(zhuǎn)換】 const char *asCString() const; std::string asString() const; const char *asCString() const; std::string asString() const; Int asInt() const; UInt asUInt() const; double asDouble() const; 6、【相應(yīng)的判斷函數(shù)】 bool isNull() const; bool isBool() const; bool isInt() const; bool isUInt() const; bool isIntegral() const; bool isDouble() const; bool isNumeric() const; bool isString() const; bool isArray() const; bool isObject() const; bool isConvertibleTo( ValueType other ) const; bool isValidIndex( UInt index ) const; bool isMember( const char *key ) const; bool isMember( const std::string &key ) const; 7、【清除和擴(kuò)容函數(shù)】 void clear(); void resize( UInt size ); 8、【獲取滿足相應(yīng)條件的Value】 Value get( UInt index, const Value &defaultValue ) const; Value get( const std::string &key,const Value &defaultValue ) const; Members getMemberNames() const; 9、【刪除滿足相應(yīng)條件的Value】 Value removeMember( const char* key ); Value removeMember( const std::string &key ); 10、【】 void setComment( const char *comment,CommentPlacement placement ); void setComment( const std::string &comment,CommentPlacement placement ); bool hasComment( CommentPlacement placement ) const; std::string getComment( CommentPlacement placement ) const; std::string toStyledString()const;
Reader :是用于讀取的,確切說是用于將字符串轉(zhuǎn)換為Json::Value對(duì)象的。
1、【構(gòu)造函數(shù)】 Reader(); 2、【拷貝構(gòu)造函數(shù)】 Reader( const Features &features ); 3、【將字符串或者輸入流轉(zhuǎn)換為JSON的Value對(duì)象】【下邊是相應(yīng)的parse的重載函數(shù)】 bool parse( const std::string &document, Value &root,bool collectComments = true ); bool parse(const char *beginDoc, const char *endDoc, Value &root,bool collectComments = true) bool parse( std::istream &is,Value &root,bool collectComments = true ); 4、【】 std::string getFormatedErrorMessages() const;
Writer :是一個(gè)純虛類,并不能直接使用。在此我們使用Json::Writer的子類(派生類):Json::FastWriter、Json::StyledWriter、Json::StyledStreamWriter。顧名思義,用Json::FastWriter來處理json應(yīng)該是最快的;負(fù)責(zé)將內(nèi)存中的Value對(duì)象轉(zhuǎn)換成JSON文檔,輸出到文件或者字符串中。
1、【FastWriter】
FastWriter();
virtual ~FastWriter(){}
void enableYAMLCompatibility();
virtual std::string write( const Value &root );
2、【StyledWriter】
StyledWriter();
virtual ~StyledWriter(){}
virtual std::string write( const Value &root );
3.json文件讀取(例)
3.1 json文件:
{
"face": [
{
"attribute": {
"age": {
"range": 5,
"value": 35
},
"gender": {
"confidence": 99.9995,
"value": "Male"
},
"glass": {
"confidence": 98.8995,
"value": "None"
},
"pose": {
"pitch_angle": {
"value": -0.000006
},
"roll_angle": {
"value": 5.32508
},
"yaw_angle": {
"value": -22.432627
}
},
"race": {
"confidence": 98.62100000000001,
"value": "Asian"
},
"smiling": {
"value": 97.3715
}
},
"face_id": "2f60c56506b691c0384e2694fed1c819",
"position": {
"center": {
"x": 51.463415,
"y": 25.121951
},
"eye_left": {
"x": 46.197561,
"y": 20.161
},
"eye_right": {
"x": 56.724146,
"y": 21.142171
},
"height": 22.926829,
"mouth_left": {
"x": 45.610732,
"y": 30.399024
},
"mouth_right": {
"x": 56.01561,
"y": 31.734146
},
"nose": {
"x": 49.063659,
"y": 27.171951
},
"width": 22.926829
},
"tag": ""
}
],
"img_height": 410,
"img_id": "84c20011223acd4efa0b5aa13fc2146d",
"img_width": 410,
"session_id": "42c5db376fdc4da9855d0135b5e414e2",
"url": "http://www.faceplusplus.com.cn/wp-content/themes/faceplusplus/assets/img/demo/16.jpg?v=2"
}
3.2 源碼:
#include<iostream>
#include<fstream>
#include<assert.h>
#include "json.h"
using namespace std;
int main()
{
Json::Reader reader;
Json::Value root;
ifstream is;
is.open("face.json", ios::binary);
if (reader.parse(is, root))
{
Json::StyledWriter sw; //縮進(jìn)輸出
cout << "縮進(jìn)輸出" << endl;
cout << sw.write(root) << endl << endl;
}
return 0;
}
3.3 結(jié)果圖:

總結(jié)
到此這篇關(guān)于C++操作.json文件的文章就介紹到這了,更多相關(guān)C++操作.json文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于OpenCV和C++ 實(shí)現(xiàn)圖片旋轉(zhuǎn)
這篇文章主要介紹了基于OpenCV和C++ 實(shí)現(xiàn)圖片旋轉(zhuǎn),幫助大家更好的利用c++處理圖片,感興趣的朋友可以了解下2020-12-12
C/C++中接收return返回來的數(shù)組元素方法示例
return是C++預(yù)定義的語句,它提供了種植函數(shù)執(zhí)行的一種放大,最近學(xué)習(xí)中遇到了相關(guān)return的內(nèi)容,覺著有必要總結(jié)一下,這篇文章主要給大家介紹了關(guān)于C/C++中如何接收return返回來的數(shù)組元素的相關(guān)資料,需要的朋友可以參考下。2017-12-12
Qt數(shù)據(jù)庫應(yīng)用之通用數(shù)據(jù)庫同步
數(shù)據(jù)庫同步的主要功能是將本地的數(shù)據(jù)庫記錄同步到遠(yuǎn)程的數(shù)據(jù)庫。本文將利用Qt實(shí)現(xiàn)通用數(shù)據(jù)庫同步功能,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-03-03
C++ Vector 動(dòng)態(tài)數(shù)組的實(shí)現(xiàn)
這篇文章主要介紹了C++ Vector 動(dòng)態(tài)數(shù)組的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01
詳解c++ atomic原子編程中的Memory Order
在多核編程中,我們使用內(nèi)核對(duì)象【如:事件對(duì)象(Event)、互斥量對(duì)象(Mutex,或互斥體對(duì)象)、信號(hào)量對(duì)象(Semaphore)等】來避免多個(gè)線程修改同一個(gè)數(shù)據(jù)時(shí)產(chǎn)生的競(jìng)爭(zhēng)條件。本文將詳細(xì)介紹c++ atomic原子編程中的Memory Order。2021-06-06

