环境: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;
}