C++ Json 静态库编译使用

本文详细介绍在Windows环境下,如何使用Visual Studio 2017配置并应用Jsoncpp库进行JSON数据的读写操作。包括下载、配置、编译及使用步骤,并提供代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

环境:Win7 x64,VS2017

介绍:C++ 调用Json库进行简单读写

操作步骤

1. 下载地址:https://github.com/open-source-parsers/jsoncpp

2. 解压后使用CMake工具进行配置,得到 JSONCPP.sln文件

3. 打开.sln文件,找到项目 jsoncpp_lib 下 json_writer.cpp,代码处添加红色部分,用于支持中文

4. Debug/Release版本单独编译

5. 将头文件和lib文件摘取出来

头文件位置:操作步骤1中,解压后include文件夹

lib文件位置:操作步骤3中 项目 jsoncpp_lib 输出目录的位置,Debug/Release单独分开

使用配置

1.新建一个项目,项目属性中设置:附加包含目录为头文件所在位置,附加库目录为lib所在位置,附加依赖项添加 jsoncpp.lib;

2.添加测试代码:

#pragma warning (disable:4996)

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

namespace
{
    std::string filePath = "D:\\TestJsonFile";
    std::string stringAttrName = "stringValue";
    std::string doubleAttrName = "doubleValue";
    std::string intAttrName = "intValue";

    void WriteFile()
    {
        Json::Value root;

        root[stringAttrName].append("1234");
        root[stringAttrName].append("5678");
        root[stringAttrName].append("我爱你  中国!");
        root[stringAttrName].append("My Name Is You");
        root[stringAttrName].append("D::\\abc_123.txt");

        root[doubleAttrName].append(100.99);

        root[intAttrName].append(50);

        Json::StyledWriter sw;
        std::ofstream os;
        os.open(filePath.c_str());
        os << sw.write(root);
        os.close();
    }
        

    void ReadFile()
    {
        Json::Reader reader;
        Json::Value root;

        ifstream in(filePath.c_str(), ios::binary);
        if (!in.is_open())
        {
            return;
        }

        if (reader.parse(in, root))
        {
            int num = 0;
            int size = 0;

            Json::Value::Members members = root.getMemberNames();
            size = root[stringAttrName].size();
            std::vector<std::string> stringValues;
            for (int i = 0; i < size; ++i)
            {
                stringValues.push_back(root[stringAttrName][i].asString());
            }


            size = root[doubleAttrName].size();
            std::vector<double> doubleValues;
            for (int i = 0; i < size; ++i)
            {
                doubleValues.push_back(root[doubleAttrName][i].asDouble());
            }

            size = root[intAttrName].size();
            std::vector<int> intValues;
            for (int i = 0; i < size; ++i)
            {
                intValues.push_back(root[intAttrName][i].asInt());
            }
        }
    }
}

int main()
{
    WriteFile();
    ReadFile();

    return 0;
}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值