JsonCpp使用方法詳解


JSON全稱為JavaScript ObjectNotation,它是一種輕量級的數據交換格式,易於閱讀、編寫、解析。jsoncpp是c++解析JSON串常用的解析庫之一。

jsoncpp中主要的類:

Json::Value:可以表示所有支持的類型,如:int , double ,string , object, array等。其包含節點的類型判斷(isNull,isBool,isInt,isArray,isMember,isValidIndex等),類型獲取(type),類型轉換(asInt,asString等),節點獲取(get,[]),節點比較(重載<,<=,>,>=,==,!=),節點操作(compare,swap,removeMember,removeindex,append等)等函數。

Json::Reader:將文件流或字符串創解析到Json::Value中,主要使用parse函數。Json::Reader的構造函數還允許用戶使用特性Features來自定義Json的嚴格等級。

Json::Writer:與JsonReader相反,將Json::Value轉換成字符串流等,Writer類是一個純虛類,並不能直接使用。在此我們使用 Json::Writer 的子類:Json::FastWriter(將數據寫入一行,沒有格式),Json::StyledWriter(按json格式化輸出,易於閱讀)。

Json::Reader可以通過對Json源目標進行解析,得到一個解析好了的Json::Value,通常字符串或者文件輸入流可以作為源目標。


如下Json文件example.json:

 

  1.  
    {
  2.  
    "encoding" : "UTF-8",
  3.  
    "plug-ins" : [
  4.  
    "python",
  5.  
    "c++",
  6.  
    "ruby"
  7.  
    ],
  8.  
    "indent" : { "length" : 3, "use_space": true }
  9.  
    "tab":null
  10.  
    }


使用Json::Reader對Json文件進行解析:

 

 

  1.  
    Json::Value root;
  2.  
    Json::Reader reader;
  3.  
    std::ifstream ifs("example.json");//open file example.json
  4.  
     
  5.  
    if(!reader.parse(ifs, root)){
  6.  
    // fail to parse
  7.  
    }
  8.  
    else{
  9.  
    // success
  10.  
    std::cout <<root["encoding"].asString()<<endl;
  11.  
    std::cout<<root["indent"]["length"].asInt()<<endl;
  12.  
    }


使用Json::Reader對字符串進行解析:

 

 

  1.  
    Json::Value root;
  2.  
    Json::Reader reader;
  3.  
    const char* s = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}";
  4.  
    if(!reader.parse(s, root)){
  5.  
    // "parse fail";
  6.  
    }
  7.  
    else{
  8.  
    std::cout << root["uploadid"].asString();//print "UP000000"
  9.  
    }


Json::Writer 和 Json::Reader相反,是把Json::Value對象寫到string對象中,而且Json::Writer是個抽象類,被兩個子類Json::FastWriter和Json::StyledWriter繼承。 
簡單來說FastWriter就是無格式的寫入,這樣的Json看起來很亂沒有格式,而StyledWriter就是帶有格式的寫入,看起來會比較友好。

 

 

  1.  
    Json::Value root;
  2.  
    Json::Reader reader;
  3.  
    Json::FastWriter fwriter;
  4.  
    Json::StyledWriter swriter;
  5.  
     
  6.  
    if(! reader.parse("example.json", root)){
  7.  
    // parse fail
  8.  
    return 0;
  9.  
    }
  10.  
    std::string str = fwriter(root);
  11.  
    std::ofstream ofs("example_fast_writer.json");
  12.  
    ofs << str;
  13.  
    ofs.close();
  14.  
     
  15.  
    str = swriter(root);
  16.  
    ofs.open("example_styled_writer.json");
  17.  
    ofs << str;
  18.  
    ofs.close();
  19.  
     
  20.  
    結果1:example_styled_writer.json:
  21.  
    {
  22.  
    "encoding" : "UTF-8",
  23.  
    "plug-ins" : [
  24.  
    "python",
  25.  
    "c++",
  26.  
    "ruby"
  27.  
    ],
  28.  
    "indent" : { "length" : 3, "use_space": true }
  29.  
    "tab":null
  30.  
    }
  31.  
     
  32.  
    結果2:example_fast_writer.json:
  33.  
    {"encoding" : "UTF-8","plug-ins" : ["python","c++","ruby"],"indent" : { "length" : 3, "use_space": true}}


Json其它函數的應用:
1、判斷KEY值是否存在:

 

 

  1.  
    if(root.isMember("encoding")){
  2.  
    std::cout <<"encoding is a member"<<std::endl;
  3.  
    }
  4.  
    else{
  5.  
    std::cout<<"encoding is not a member"<<std::endl;
  6.  
    }


2、判斷Value是否為null:

 

if(root["tab"].isNull()){
    std::cout << "isNull" <<std::endl;//print isNull
}

 

完整例子使用舉例來自於CSDN下載網友的程序:

源碼下載地址:http://download.csdn.net/download/woniu211111/9966907

 

  1.  
    /********************************************************
  2.  
    Copyright (C), 2016-2017,
  3.  
    FileName: main
  4.  
    Author: woniu201
  5.  
    Email: wangpengfei.201@163.com
  6.  
    Created: 2017/09/06
  7.  
    Description:use jsoncpp src , not use dll, but i also provide dll and lib.
  8.  
    ********************************************************/
  9.  
     
  10.  
    #include "stdio.h"
  11.  
    #include <string>
  12.  
    #include "jsoncpp/json.h"
  13.  
     
  14.  
    using namespace std;
  15.  
     
  16.  
    /************************************
  17.  
    @ Brief: read file
  18.  
    @ Author: woniu201
  19.  
    @ Created: 2017/09/06
  20.  
    @ Return: file data
  21.  
    ************************************/
  22.  
    char *getfileAll(char *fname)
  23.  
    {
  24.  
    FILE *fp;
  25.  
    char *str;
  26.  
    char txt[1000];
  27.  
    int filesize;
  28.  
    if ((fp=fopen(fname,"r"))==NULL){
  29.  
    printf("open file %s fail \n",fname);
  30.  
    return NULL;
  31.  
    }
  32.  
     
  33.  
    /*
  34.  
    獲取文件的大小
  35.  
    ftell函數功能:得到流式文件的當前讀寫位置,其返回值是當前讀寫位置偏離文件頭部的字節數.
  36.  
    */
  37.  
    fseek(fp,0,SEEK_END);
  38.  
    filesize = ftell(fp);
  39.  
     
  40.  
    str=(char *)malloc(filesize);
  41.  
    str[0]=0;
  42.  
     
  43.  
    rewind(fp);
  44.  
    while((fgets(txt,1000,fp))!=NULL){
  45.  
    strcat(str,txt);
  46.  
    }
  47.  
    fclose(fp);
  48.  
    return str;
  49.  
    }
  50.  
     
  51.  
    /************************************
  52.  
    @ Brief: write file
  53.  
    @ Author: woniu201
  54.  
    @ Created: 2017/09/06
  55.  
    @ Return:
  56.  
    ************************************/
  57.  
    int writefileAll(char* fname,const char* data)
  58.  
    {
  59.  
    FILE *fp;
  60.  
    if ((fp=fopen(fname, "w")) == NULL)
  61.  
    {
  62.  
    printf("open file %s fail \n", fname);
  63.  
    return 1;
  64.  
    }
  65.  
     
  66.  
    fprintf(fp, "%s", data);
  67.  
    fclose(fp);
  68.  
     
  69.  
    return 0;
  70.  
    }
  71.  
     
  72.  
    /************************************
  73.  
    @ Brief: parse json data
  74.  
    @ Author: woniu201
  75.  
    @ Created: 2017/09/06
  76.  
    @ Return:
  77.  
    ************************************/
  78.  
    int parseJSON(const char* jsonstr)
  79.  
    {
  80.  
    Json::Reader reader;
  81.  
    Json::Value resp;
  82.  
     
  83.  
    if (!reader.parse(jsonstr, resp, false))
  84.  
    {
  85.  
    printf("bad json format!\n");
  86.  
    return 1;
  87.  
    }
  88.  
    int result = resp["Result"].asInt();
  89.  
    string resultMessage = resp["ResultMessage"].asString();
  90.  
    printf("Result=%d; ResultMessage=%s\n", result, resultMessage.c_str());
  91.  
     
  92.  
    Json::Value & resultValue = resp["ResultValue"];
  93.  
    for (int i=0; i <resultValue.size(); i++)
  94.  
    {
  95.  
    Json::Value subJson = resultValue[i];
  96.  
    string cpuRatio = subJson["cpuRatio"].asString();
  97.  
    string serverIp = subJson["serverIp"].asString();
  98.  
    string conNum = subJson["conNum"].asString();
  99.  
    string websocketPort = subJson["websocketPort"].asString();
  100.  
    string mqttPort = subJson["mqttPort"].asString();
  101.  
    string ts = subJson["TS"].asString();
  102.  
     
  103.  
    printf("cpuRatio=%s; serverIp=%s; conNum=%s; websocketPort=%s; mqttPort=%s; ts=%s\n",cpuRatio.c_str(), serverIp.c_str(),
  104.  
    conNum.c_str(), websocketPort.c_str(), mqttPort.c_str(), ts.c_str());
  105.  
    }
  106.  
    return 0;
  107.  
    }
  108.  
     
  109.  
    /************************************
  110.  
    @ Brief: create json data
  111.  
    @ Author: woniu201
  112.  
    @ Created: 2017/09/06
  113.  
    @ Return:
  114.  
    ************************************/
  115.  
    int createJSON()
  116.  
    {
  117.  
    Json::Value req;
  118.  
    req["Result"] = 1;
  119.  
    req["ResultMessage"] = "200";
  120.  
     
  121.  
    Json::Value object1;
  122.  
    object1["cpuRatio"] = "4.04";
  123.  
    object1["serverIp"] = "42.159.116.104";
  124.  
    object1["conNum"] = "1";
  125.  
    object1["websocketPort"] = "0";
  126.  
    object1["mqttPort"] = "8883";
  127.  
    object1["TS"] = "1504665880572";
  128.  
    Json::Value object2;
  129.  
    object2["cpuRatio"] = "2.04";
  130.  
    object2["serverIp"] = "42.159.122.251";
  131.  
    object2["conNum"] = "2";
  132.  
    object2["websocketPort"] = "0";
  133.  
    object2["mqttPort"] = "8883";
  134.  
    object2["TS"] = "1504665896981";
  135.  
     
  136.  
    Json::Value jarray;
  137.  
    jarray.append(object1);
  138.  
    jarray.append(object2);
  139.  
     
  140.  
    req["ResultValue"] = jarray;
  141.  
     
  142.  
    Json::FastWriter writer;
  143.  
    string jsonstr = writer.write(req);
  144.  
     
  145.  
    printf("%s\n", jsonstr.c_str());
  146.  
     
  147.  
    writefileAll("createJson.json", jsonstr.c_str());
  148.  
    return 0;
  149.  
    }
  150.  
     
  151.  
    int main()
  152.  
    {
  153.  
    /*讀取Json串,解析Json串*/
  154.  
    char* json = getfileAll("parseJson.json");
  155.  
    parseJSON(json);
  156.  
    printf("===============================\n");
  157.  
     
  158.  
    /*組裝Json串*/
  159.  
    createJSON();
  160.  
     
  161.  
    getchar();
  162.  
    return 1;
  163.  
    }


參考:

 

http://open-source-parsers.github.io/jsoncpp-docs/doxygen/index.html

http://blog.csdn.net/yc461515457/article/details/52749575


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM