c++跨平台json文件操作--rapidjson

rapidjson

RapidJSON 是一个 C++ 的 JSON 解析器及生成器,方便简单,不用编译,直接将include文件夹放到项目目录下就可以使用。

生成json文件

我们以生成简单的学生信息示例。

json文件实例

{
  "Info": [
    {
      "Age": 11,
      "ID": "1",
      "Name": "student_1"
    },
    {
      "Age": 12,
      "ID": "2",
      "Name": "student_2"
    },
    {
      "Age": 13,
      "ID": "3",
      "Name": "student_3"
    }
  ]
}

源码

  1. 首先创建学生信息结构体。
  2. 创建一个vector保存多个学生信息。
  3. 循环生成学生信息,压入vector。
  4. 读取vector写入json,先判断是否存在json文件,不存在创建一个空的json。 { "Info": [] }
  5. 读取json文件为字符串。
  6. 将字符串载入rapidjson进行解析,然后再写入数据。
#include <iostream>
#include <vector>
#include <string>
#include "include/rapidjson/document.h"
#include "include/rapidjson/prettywriter.h"
#include "include/rapidjson/stringbuffer.h"
using namespace rapidjson;
using namespace std;
typedef struct
{
	string ID;
	string Name;
	int Age;
}Student;
rapidjson::Value infoArray;
vector<Student> student_list;
string readfile(const char* filename) {
	FILE* fp = fopen(filename, "rb");
	if (!fp) {
		printf("open failed! file: %s", filename);
		return "";
	}
	char* buf = new char[1024 * 16];
	int n = fread(buf, 1, 1024 * 16, fp);
	fclose(fp);

	string result;
	if (n >= 0) {
		result.append(buf, 0, n);
	}
	delete[]buf;
	return result;
}
void writeJson(string jsonFilePath,Student& student)
{
	string jsonstr = readfile(jsonFilePath.c_str());
	//cout << jsonstr << endl;
	if (jsonstr == "")
	{
		rapidjson::Document doc;
		rapidjson::Document::AllocatorType& allocator = doc.GetAllocator(); //获取分配器
		doc.SetObject();    //将当前的Document设置为一个object,也就是说,整个Document是一个Object类型的dom元素
		rapidjson::Value array(rapidjson::Type::kArrayType);
		doc.AddMember("Info", array, allocator);    //添加字符串值
		//生成字符串
		rapidjson::StringBuffer buffer;
		rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
		doc.Accept(writer);
		//std::string strJson = buffer.GetString();
		//写到文件
		FILE* myFile = fopen(jsonFilePath.c_str(), "w");  //windows平台要使用wb
		if (myFile) {
			//cout<<buffer.GetString()<<endl;
			fputs(buffer.GetString(), myFile);
			fclose(myFile);
		}
	}
	jsonstr = readfile(jsonFilePath.c_str());
	rapidjson::Document doc;
	doc.Parse(jsonstr.c_str());
	rapidjson::Value& arrays = doc["Info"];
	//判断读取成功与否 和 是否为数组类型  
	rapidjson::Document::AllocatorType& allocator = doc.GetAllocator(); //获取分配器
	doc.SetObject();    //将当前的Document设置为一个object,也就是说,整个Document是一个Object类型的dom元素
	rapidjson::Value people(rapidjson::kObjectType); //生成people
	rapidjson::Value val;
	people.AddMember("Age", val.SetInt(student.Age), allocator);
	people.AddMember("ID", val.SetString(student.ID.c_str(), allocator), allocator);
	people.AddMember("Name", val.SetString(student.Name.c_str(), allocator), allocator);
	arrays.PushBack(people, allocator);           //添加到数组
	//添加属性
	doc.AddMember("Info", arrays, allocator);    //添加字符串值
		//生成字符串
	rapidjson::StringBuffer buffer;
	rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
	doc.Accept(writer);
	std::string strJson = buffer.GetString();
	//写到文件
	FILE* myFile = fopen(jsonFilePath.c_str(), "w");  //windows平台要使用wb
	if (myFile) {
		fputs(buffer.GetString(), myFile);
		fclose(myFile);
	}
}

int main()
{
	string jsonFilePath = "student_info.json";
	for (int i = 1; i <= 10; i++)
	{
		Student student_tmp;
		student_tmp.Age = i + 10;
		student_tmp.ID = to_string(i);
		student_tmp.Name = "student_" + to_string(i);
		student_list.push_back(student_tmp);
	}
	for (size_t i = 0; i < student_list.size(); i++)
	{
		/*cout << student_list[i].Age << endl;
		cout << student_list[i].ID << endl;
		cout << student_list[i].Name << endl;
		cout << endl;*/
		writeJson(jsonFilePath, student_list[i]);
	}

写入成功示例

在这里插入图片描述

读取json文件

  1. 先读取json文件为字符串。
  2. 将第一个array读取。
  3. 遍历array,提取数据。

源码

#include <iostream>
#include <vector>
#include <string>
#include "include/rapidjson/document.h"
#include "include/rapidjson/prettywriter.h"
#include "include/rapidjson/stringbuffer.h"
using namespace rapidjson;
using namespace std;

rapidjson::Value infoArray;
void shou_json(string jsonFilePath) {
	string jsonstr = readfile(jsonFilePath.c_str());
	//cout << jsonstr << endl;
	Document doc;
	doc.Parse(jsonstr.c_str());
	//判断读取成功与否 和 是否为数组类型  
	infoArray = doc["Info"];
	for (int i = 0; i < infoArray.Size(); i++)
		{
		const Value& a = infoArray[i];
		int Age = a["Age"].GetInt();
		string ID = a["ID"].GetString();
		string Name = a["Name"].GetString();
		cout <<"age: "<< Age << " id: " << ID << " name: " << Name << endl;
		}
}
int main()
{
	string jsonFilePath = "student_info.json";
	shou_json(jsonFilePath);
}

读取成功示例

在这里插入图片描述

整体源码

#include <iostream>
#include <vector>
#include <string>
#include "include/rapidjson/document.h"
#include "include/rapidjson/prettywriter.h"
#include "include/rapidjson/stringbuffer.h"
using namespace rapidjson;
using namespace std;
typedef struct
{
	string ID;
	string Name;
	int Age;
}Student;
rapidjson::Value infoArray;
vector<Student> student_list;

string readfile(const char* filename) {
	FILE* fp = fopen(filename, "rb");
	if (!fp) {
		printf("open failed! file: %s", filename);
		return "";
	}
	char* buf = new char[1024 * 16];
	int n = fread(buf, 1, 1024 * 16, fp);
	fclose(fp);

	string result;
	if (n >= 0) {
		result.append(buf, 0, n);
	}
	delete[]buf;
	return result;
}
void writeJson(string jsonFilePath,Student& student)
{
	string jsonstr = readfile(jsonFilePath.c_str());
	//cout << jsonstr << endl;
	if (jsonstr == "")
	{
		rapidjson::Document doc;
		rapidjson::Document::AllocatorType& allocator = doc.GetAllocator(); //获取分配器
		doc.SetObject();    //将当前的Document设置为一个object,也就是说,整个Document是一个Object类型的dom元素
		rapidjson::Value array(rapidjson::Type::kArrayType);
		doc.AddMember("Info", array, allocator);    //添加字符串值
		//生成字符串
		rapidjson::StringBuffer buffer;
		rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
		doc.Accept(writer);
		//std::string strJson = buffer.GetString();
		//写到文件
		FILE* myFile = fopen(jsonFilePath.c_str(), "w");  //windows平台要使用wb
		if (myFile) {
			//cout<<buffer.GetString()<<endl;
			fputs(buffer.GetString(), myFile);
			fclose(myFile);
		}
	}
	jsonstr = readfile(jsonFilePath.c_str());
	rapidjson::Document doc;
	doc.Parse(jsonstr.c_str());
	rapidjson::Value& arrays = doc["Info"];
	//判断读取成功与否 和 是否为数组类型  
	rapidjson::Document::AllocatorType& allocator = doc.GetAllocator(); //获取分配器
	doc.SetObject();    //将当前的Document设置为一个object,也就是说,整个Document是一个Object类型的dom元素
	rapidjson::Value people(rapidjson::kObjectType); //生成people
	rapidjson::Value val;
	people.AddMember("Age", val.SetInt(student.Age), allocator);
	people.AddMember("ID", val.SetString(student.ID.c_str(), allocator), allocator);
	people.AddMember("Name", val.SetString(student.Name.c_str(), allocator), allocator);
	arrays.PushBack(people, allocator);           //添加到数组
	//添加属性
	doc.AddMember("Info", arrays, allocator);    //添加字符串值
		//生成字符串
	rapidjson::StringBuffer buffer;
	rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
	doc.Accept(writer);
	std::string strJson = buffer.GetString();
	//写到文件
	FILE* myFile = fopen(jsonFilePath.c_str(), "w");  //windows平台要使用wb
	if (myFile) {
		fputs(buffer.GetString(), myFile);
		fclose(myFile);
	}
}
void shou_json(string jsonFilePath) {
	string jsonstr = readfile(jsonFilePath.c_str());
	//cout << jsonstr << endl;
	Document doc;
	doc.Parse(jsonstr.c_str());
	//判断读取成功与否 和 是否为数组类型  
	infoArray = doc["Info"];
	for (int i = 0; i < infoArray.Size(); i++)
		{
		const Value& a = infoArray[i];
		int Age = a["Age"].GetInt();
		string ID = a["ID"].GetString();
		string Name = a["Name"].GetString();
		cout <<"age: "<< Age << " id: " << ID << " name: " << Name << endl;
		}
}

int main()
{
	string jsonFilePath = "student_info.json";
	for (int i = 1; i <= 10; i++)
	{
		Student student_tmp;
		student_tmp.Age = i + 10;
		student_tmp.ID = to_string(i);
		student_tmp.Name = "student_" + to_string(i);
		student_list.push_back(student_tmp);
	}
	for (size_t i = 0; i < student_list.size(); i++)
	{
		/*cout << student_list[i].Age << endl;
		cout << student_list[i].ID << endl;
		cout << student_list[i].Name << endl;
		cout << endl;*/
		writeJson(jsonFilePath, student_list[i]);
	}
	shou_json(jsonFilePath);
}

vs2019遇到问题,Release x64

“error C4996: ‘fopen’: This function or variable may be unsafe. Consider using fopen_s instead”
解决办法:
项目----》 XX属性 ----》C++ —>预处理器 —》在预处理器定义添加“_CRT_SECURE_NO_WARNINGS”

rapidjson include文件地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智能视界探索者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值