rapidjson的下载以及简单使用
一、rapidjson的下载
下载地址:https://github.com/Tencent/rapidjson
二、rapidjson的使用
1.windows平台下的使用
(1) 将所下载文件中的include目录复制到项目文件夹
(2) 点击项目 --> 属性 -->配置属性–>包含目录把include所对应的路径添加进去
2.linux下的使用
(1)也是将include文件夹复制到对应的项目文件夹里
(2)使用g++ -I /linux上include的路径 main.cpp -o main 就会生成main的可执行文件
二、rapidjson 的简单使用及读写txt文件
1.给json插入字段
#include <iostream>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/filereadstream.h"
#include "rapidjson/filewritestream.h"
#include "rapidjson/istreamwrapper.h"
#include "rapidjson/ostreamwrapper.h"
#include <fstream>
using namespace std;
using namespace rapidjson;
Document jsonDoc; //生成一个dom元素Document
Document::AllocatorType &allocator = jsonDoc.GetAllocator(); //获取分配器
jsonDoc.SetObject();
Value value1(kObjectType);
value1.AddMember("name", "语文", allocator); // string型(给字段赋值,key必须为string型下同)
value1.AddMember("score", 80, allocator); // 整型
value1.AddMember("right", true, allocator); // bool
value1.AddMember("percent", 12.3456789123, allocator);//浮点型
2.将json写入txt
void writeFiles(string str,string FileName) //写入json文件
{
Document docu;
docu.Parse(str.c_str());//将字符串载入json
ofstream ofs(FileName.c_str());
OStreamWrapper osw(ofs);
Writer<OStreamWrapper> writer3(osw);
docu.Accept(writer3);
}
3.读取txt
void ReadJson(Document d,string FileName)
{
FILE* fp = fopen(FileName.c_str(), "r+");
char readBuffer[65536];
FileReadStream is(fp, readBuffer,sizeof(readBuffer));
d.ParseStream(is);
fclose(fp);
return d;
}