zoukankan      html  css  js  c++  java
  • C++简单使用Jsoncpp来读取写入json文件

    一、源码编译

    C++操作json字符串最好的库应该就是jsoncpp了,开源并且跨平台。它可以从这里下载

    下载后将其解压到任意目录,它默认提供VS2003和VS2010的工程文件,使用VS2010可以直接打开makefilesmsvc2010目录下的sln文件。

    工程文件提供Jsoncpp的win32和win64静态库生成。点击生成--批生成选择需要生成的配置后即可生成jsoncpp静态库。生成的文件在makefilesmsvc2010(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()<<"	"<<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()<<"	"<<sit.name()<<endl;
            }
        }
        return 0;
    }

    三、运行结果

    image

    四、相关下载

    代码下载

  • 相关阅读:
    最主要的商业模式
    Linux-清除rootpassword
    Drupal 关于节点(nodes)的理解
    hdu4240 求一条流量最大的路/(此题网上百分之90以上算法是错误的)
    LeetCode Next Permutation
    关于使用strtok的一个小问题
    SDUT--Pots(二维BFS)
    微信 小程序组件 滑动导航和获取元素实际高度
    微信 小程序组件 电话
    微信小程序组件 客服
  • 原文地址:https://www.cnblogs.com/Reyzal/p/5494324.html
Copyright © 2011-2022 走看看