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

四、相关下载

代码下载

posted @ 2016-05-15 00:59  reyzal  阅读(23002)  评论(0编辑  收藏  举报