溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么使用C++操作.json文件

發(fā)布時(shí)間:2022-08-12 10:12:32 來(lái)源:億速云 閱讀:163 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容介紹了“怎么使用C++操作.json文件”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

    1.JSON簡(jiǎn)介

    1.1 什么是JSON:

    JSON是一種純字符串形式的數(shù)據(jù),它本身不提供任何方法(函數(shù)),非常適合在網(wǎng)絡(luò)中進(jìn)行傳輸。JavaScript、PHP、Java、Python、C++等編程語(yǔ)言都內(nèi)置了處理JSON數(shù)據(jù)的方法。

    JSON 是基于 JavaScript(Standard ECMA-262 3rd Edition - December 1999)的一個(gè)子集,是一種開放的、輕量級(jí)的數(shù)據(jù)交換格式,采用獨(dú)立于編程語(yǔ)言的文本格式來(lái)存儲(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來(lái)說(shuō),json格式更加明確,獲取重要信息非常方便。

      相對(duì)于xml來(lái)說(shuō),json格式更加簡(jiǎn)潔,存儲(chǔ)同樣的文件,花費(fèi)的內(nèi)存更小。

      相對(duì)于Excel來(lái)說(shuō),json更適合存儲(chǔ)字符類文件。Excel相當(dāng)于比較簡(jiǎn)單的數(shù)據(jù)庫(kù)了。

      相對(duì)于數(shù)據(jù)庫(kù)來(lái)說(shuō),json更加方便,數(shù)據(jù)庫(kù)我們還需要做一些設(shè)置,安裝一些軟件。json可以直接使用。
     

    缺點(diǎn):

      只有一種數(shù)字類型:JSON中只能支持IEEE-754雙精度浮點(diǎn)格式,因此我們無(wú)法使用JSON來(lái)存儲(chǔ)許多編程語(yǔ)言中多樣化的數(shù)字類型;

      沒(méi)有日期類型:在JSON中我們只能通過(guò)日期的字符串(例如:1970-01-01)或者時(shí)間戳(例如:1632366361)來(lái)表示日期;

      沒(méi)有注釋:在JSON中無(wú)法添加注釋;

      冗長(zhǎng):雖然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ù)庫(kù)、Cookie、Session中。要使用存儲(chǔ)好的JSON數(shù)據(jù)也非常簡(jiǎn)單,不同的編程語(yǔ)言中提供了不同的方法來(lái)檢索和解析JSON數(shù)據(jù),今天我們的重點(diǎn)就是使用C++來(lái)操作.json文件。而C++主要使用jsoncpp這個(gè)跨平臺(tái)的開源庫(kù)來(lái)實(shí)現(xiàn)對(duì).json文件的各類操作。

    2.jsoncpp庫(kù)介紹

    2.1 jsoncpp庫(kù)的配置使用:

    這里我就不按照網(wǎng)上常規(guī)的方式來(lái)介紹了,常規(guī)的方法無(wú)非是關(guān)于下載jsoncpp庫(kù),然后使用Windows編譯(vs2015),最后整理出include及l(fā)ib來(lái)使用jsoncpp庫(kù)。我這里是整理好的,是直接把include里的所有文件集合成json.h以及json.cpp。用的時(shí)候直接把這些文件包含進(jìn)自己的項(xiàng)目一起編譯即可。

    怎么使用C++操作.json文件

    2.2 jsoncpp庫(kù)內(nèi)部構(gòu)成:

    jsoncpp主要包含三個(gè)class(類):Value、Reader、Writer。注意Json::Value只能處理ANSI類型的字符串,如果C++程序是用Unicode編碼的,最好加一個(gè)Adapt類來(lái)適配。

    Value: 是jsoncpp中最基本、最重要的類,用于表示各種類型的對(duì)象,jsoncpp支持的對(duì)象類型可見(jiàn)下面的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 :是用于讀取的,確切說(shuō)是用于將字符串轉(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來(lái)處理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é)果圖:

    怎么使用C++操作.json文件

    “怎么使用C++操作.json文件”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

    向AI問(wèn)一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

    c++
    AI