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"
}
]
}
源码
- 首先创建学生信息结构体。
- 创建一个vector保存多个学生信息。
- 循环生成学生信息,压入vector。
- 读取vector写入json,先判断是否存在json文件,不存在创建一个空的json。
{ "Info": [] }
- 读取json文件为字符串。
- 将字符串载入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文件
- 先读取json文件为字符串。
- 将第一个array读取。
- 遍历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”