C++簡單使用Jsoncpp來讀取寫入json文件


一、源碼編譯

C++操作json字符串最好的庫應該就是jsoncpp了,開源並且跨平台。它可以從這里下載

下載后將其解壓到任意目錄,它默認提供VS2003和VS2010的工程文件,使用VS2010可以直接打開makefiles\msvc2010目錄下的sln文件。

工程文件提供Jsoncpp的win32和win64靜態庫生成。點擊生成--批生成選擇需要生成的配置后即可生成jsoncpp靜態庫。生成的文件在makefiles\msvc2010\(x64\)Debug(Release)\目錄下。

二、測試工程

新建Win32控制台項目,為了區分Debug和Release版本,將Debug目錄下的lib_json.lib改名為lib_json_d.lib,復制到新建的工程目錄。

將jsoncpp目錄下的include文件夾也復制到工程目錄

image

修改工程屬性如下

image

image

主文件代碼如下:

// testJson.cpp : 定義控制台應用程序的入口點。
//

#include "stdafx.h"
#include <iostream>
#include <fstream>
//添加需要的頭文件
#include "include/json/json.h"

using namespace std;

//鏈接需要的庫文件
#ifdef _DEBUG
#pragma comment(lib,"lib_json_d.lib")
#else
#pragma comment(lib,"lib_json.lib")
#endif

int _tmain(int argc, _TCHAR* argv[])
{
    cout<<"測試json寫入"<<endl;
    Json::Value jsonRoot;
    Json::Value jsonItem;
    jsonItem["item1"] = "第一個條目";
    jsonItem["item2"] = "第二個條目";
    jsonItem["item3"] = 3;
    jsonRoot.append(jsonItem);
    jsonItem.clear();//清除上面已經賦值的項
    jsonItem["First"]="1";
    jsonItem["Second"]=2;
    jsonItem["Third"]=3.0F;
    jsonRoot.append(jsonItem);
    cout<<jsonRoot.toStyledString()<<endl;

    cout<<"測試json寫入到文件"<<endl;

    ofstream ofs;
    ofs.open("test1.json");
    ofs<<jsonRoot.toStyledString();
    ofs.close();

    cout<<"測試json讀取"<<endl;
    string sJson = jsonRoot.toStyledString();
    jsonRoot.clear();
    Json::Reader jsonReader;
    if (!jsonReader.parse(sJson,jsonRoot))
    {
        return -1;
    }
    for (auto it = jsonRoot.begin();
        it!=jsonRoot.end();
        it++)
    {
        for (auto sit = it->begin();
            sit != it->end();
            sit++)
        {
            cout<<sit.key()<<"\t"<<sit.name()<<endl;
        }
    }
    cout<<"測試讀取json文件"<<endl;
    ifstream ifs;
    ifs.open("test1.json");

    jsonRoot.clear();
    if (!jsonReader.parse(ifs, jsonRoot))
    {
        return -1;
    }
    ifs.close();
    for (auto it = jsonRoot.begin();
        it!=jsonRoot.end();
        it++)
    {
        for (auto sit = it->begin();
            sit != it->end();
            sit++)
        {
            cout<<sit.key()<<"\t"<<sit.name()<<endl;
        }
    }
    return 0;
}

三、運行結果

image

四、相關下載

代碼下載


免責聲明!

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



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