JsonCpp解析和讀寫Json字符串


時間:2020年5月17日11:37:10

JsonCPP 改版了,以前的 Json::Reader,  Json::Parse被棄用了,得用新的方法。

JsonCpp項目地址:https://github.com/open-source-parsers/jsoncpp/blob/master/doc/jsoncpp.dox

 

 

下面的Demo,可以實現 讀取json字符串、創造json對象、輸出json字符串。

主要的函數是這4個函數:

Json::StreamWriterBuilder,
Json::writeString
Json::CharReaderBuilder
Json::parseFromStream

 

 

#include <iostream>
#include <string>
#include "../include/json/json.h"
using namespace std;

//  g++ demo1.cpp -I ../include  ./lib_json/libjsoncpp.a -std=c++11 

int main()
{
    Json::Value objectRoot;
    objectRoot["id"] = 1234;
    objectRoot["name"] = "henry";


    cout <<"------------StreamWriterBuilder------------"<<endl;
    Json::StreamWriterBuilder wbuilder;
    wbuilder["indentation"] = "";
//    wbuilder["indentation"] = "\t";
    std::string document = Json::writeString(wbuilder, objectRoot);
    cout <<"StreamWriterBuilder: "<<document<<endl;

 
 
    char strBuf[]="{ \"id\":666, \"name\":\"henryHe\"}";
    cout <<"------------CharReaderBuilder------------"<<endl;
    std::istringstream iss(strBuf);  ////必須得強制類型轉換
    Json::Value readValue;
    Json::CharReaderBuilder rbuilder;
    rbuilder["collectComments"] = false;
    std::string errs;
    bool ok = Json::parseFromStream(rbuilder, iss , &readValue, &errs);
    cout <<"ok: "<<ok<<endl;
    cout <<"id: "<<readValue["id"]<<endl;
    cout <<"name: "<<readValue["name"]<<endl;
    

//  const std::string rawJson = R"({"Age": 20, "Name": "colin"})";
//  const int rawJsonLength = static_cast<int>(rawJson.length());
//    cout <<   rawJsonLength<<endl;
//    cout <<   rawJson<<endl;




cout <<"hello world"<<endl;

  return 0;
}

 

 

 

 

說明:項目中的  libjsoncpp.a  是我根據 JsonCpp 工程的源碼編譯的 庫。

直接下載JsonCpp工程,解壓之后,執行

cmake ./  

make -f Makefile 

 

如果沒有安裝CMake,請看這里:https://www.cnblogs.com/music-liang/p/12900511.html

 


免責聲明!

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



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