C++ 解析Json——jsoncpp

來源:互聯網
上載者:User

標籤:one   包含   ppa   目錄   ima   使用   預設   ges   void   

Jsoncpp是個跨平台的開源庫,:http://sourceforge.net/projects/jsoncpp/,我下載的是v0.5.0,壓縮包大約104K。

方法一:使用Jsoncpp產生的lib檔案
      解壓上面下載的Jsoncpp檔案,在jsoncpp-src-0.5.0/makefiles/vs71目錄裡找到jsoncpp.sln,用VS2008版本編譯,預設產生靜態連結庫。 在工程中引用,只需要包含include/json下的標頭檔及產生的.lib檔案即可。
      如何包含lib檔案:在.cpp檔案中#pragma comment(lib."json_vc71_libmt.lib"),在工程屬性中Linker下Input中Additional Dependencies寫入lib檔案名稱字(Release下為json_vc71_libmt.lib,Debug為json_vc71_libmtd.lib)

注意:Jsoncpp的lib工程編譯選項要和VS工程中的編譯選項保持一致。如lib檔案工程編譯選項為MT(或MTd),VS工程中也要選擇MT(或MTd),否則會出現編譯錯誤問題,debug和release下產生的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三個檔案的Precompiled Header屬性設定為 Not Using Precompiled Headers,否則編譯會出現錯誤。

jsoncpp 使用詳解

jsoncpp 主要包含三種類型的 class:Value、Reader、Writer。jsoncpp 中所有對象、類名都在 namespace Json 中,包含 json.h 即可。

Json::Value 只能處理 ANSI 類型的字串,如果 C++ 程式是用 Unicode 編碼的,最好加一個 Adapt 類來適配。

// TestJsoncppCode.cpp : Defines the entry point for the console application.  02.//  03.  04.#include "stdafx.h"  05.  06.  07.#include "include/json/json.h"  08.#include <fstream>  09.#include <string>  10.  11.#pragma comment(lib,"lib_json.lib")  12.using namespace std;  13.  14.#ifdef _DEBUG  15.#define new DEBUG_NEW  16.#endif  17.  18.  19.// The one and only application object  20.  21.  22.void WriteJsonData(const char* filename)  23.{  24.    Json::Reader reader;  25.    Json::Value root; // Json::Value是一種很重要的類型,可以代表任意類型。如int, string, object, array...          26.  27.    std::ifstream is;  28.    is.open(filename, std::ios::binary);  29.    if (reader.parse(is, root))  30.    {  31.        Json::Value arrayObj;   // 構建對象    32.        Json::Value new_item, new_item1;  33.        new_item["date"] = "2011-11-11";  34.        new_item1["time"] = "11:11:11";  35.        arrayObj.append(new_item);  // 插入數群組成員    36.        arrayObj.append(new_item1); // 插入數群組成員    37.        int file_size = root["files"].size();  38.        for (int i = 0; i < file_size; ++i)  39.            root["files"][i]["exifs"] = arrayObj;   // 插入原json中   40.        std::string out = root.toStyledString();  41.        // 輸出無格式json字串    42.        Json::FastWriter writer;  43.        std::string strWrite = writer.write(root);  44.        std::ofstream ofs;  45.        ofs.open("test_write.json");  46.        ofs << strWrite;  47.        ofs.close();  48.    }  49.  50.    is.close();  51.}  52.  53.int ReadJsonFromFile(const char* filename)  54.{  55.    Json::Reader reader;// 解析json用Json::Reader     56.    Json::Value root; // Json::Value是一種很重要的類型,可以代表任意類型。如int, string, object, array...           57.  58.    std::ifstream is;  59.    is.open(filename, std::ios::binary);  60.    if (reader.parse(is, root, false))  61.    {  62.        std::string code;  63.        if (!root["files"].isNull())  // 訪問節點,Access an object value by name, create a null member if it does not exist.    64.            code = root["uploadid"].asString();  65.  66.        code = root.get("uploadid", "null").asString();// 訪問節點,Return the member named key if it exist, defaultValue otherwise.      67.  68.        int file_size = root["files"].size();  // 得到"files"的數組個數    69.        for (int i = 0; i < file_size; ++i)  // 遍曆數組    70.        {  71.            Json::Value val_image = root["files"][i]["images"];  72.            int image_size = val_image.size();  73.            for (int j = 0; j < image_size; ++j)  74.            {  75.                std::string type = val_image[j]["type"].asString();  76.                std::string url = val_image[j]["url"].asString();  77.                printf("type : %s, url : %s \n", type.c_str(), url.c_str());  78.            }  79.        }  80.    }  81.    is.close();  82.  83.    return 0;  84.}  85.  86.int main(int argc, TCHAR* argv[], TCHAR* envp[])  87.{  88.    int nRetCode = 0;  89.  90.  91.    //1.從字串解析json  92.    const char* str = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}";  93.  94.    Json::Reader reader;  95.    Json::Value root;  96.    if (reader.parse(str, root))    // reader將Json字串解析到root,root將包含Json裡所有子項目    97.    {  98.        printf("--------------從字串讀取JSON---------------\n");  99.        std::string upload_id = root["uploadid"].asString();  // 訪問節點,upload_id = "UP000000"    100.        int code = root["code"].asInt();                      // 訪問節點,code = 100   101.  102.        printf("upload_id : %s\ncode : %d \n", upload_id.c_str(), code);  103.    }  104.  105.    //2.從檔案解析json  106.    string sTempPath = "test_json.json";  107.  108.    printf("--------------從檔案讀取JSON---------------\n");  109.    ReadJsonFromFile(sTempPath.c_str());  110.  111.  112.    //3.向檔案寫入json  113.    WriteJsonData(sTempPath.c_str());  114.  115.    system("pause");  116.  117.    return nRetCode;  118.}  



C++ 解析Json——jsoncpp

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.