首先包含下头文件
#include "json/rapidjson.h"
#include "json/document.h"//前两个解析
#include "json/writer.h"
#include "json/stringbuffer.h"//后两个做添加修改删除操作
using namespace rapidjson;
//data.json文件
{
"username":"caoyang",
"levels":10,
"weapon":[1,2,3,4],
"costume":{
"clothing":"clothing",
"headpiece":"headpiece",
"shoes":"shoes"
}
}
//具体代码
//获得可写的具体文件路径
std::string path = FileUtils::getInstance() -> getWritablePath();
std::string jsonPath = path + filename;
//读取
rapidjson::Document doc;
std::string jsonstr = FileUtils::getInstance()->getStringFromFile(jsonPath);
log("%s",jsonstr.c_str());
doc.Parse<rapidjson::kParseDefaultFlags>(jsonstr.c_str());
if(doc.HasParseError()){//出错
return;
}
if(doc.HasMember("username")){
rapidjson::Value &username = doc["username"];
log("%s",username.GetString());
}
if(doc.HasMember("levels")){
rapidjson::Value &levels = doc["levels"];
log("%d",levels.GetInt());
}
if(doc.HasMember("weapon")){
if (doc["weapon"].IsArray()) {
rapidjson::Value &array = doc["weapon"];
for (int i=0; i<array.Size(); i++){
rapidjson::Value &element = array[i];
log("%d",element.GetInt());
}
}
}
log("%d",doc["weapon"][1].GetInt());
if(doc.HasMember("costume")){
if(doc["costume"].IsObject()){
rapidjson::Value &object= doc["costume"];
rapidjson::Value &clothing = object["clothing"];
log("%s",clothing.GetString());
}
}
log("%s",doc["costume"]["clothing"].GetString());
//添加
doc["costume"].AddMember("name", "zhangsan", doc.GetAllocator());
//修改
doc["costume"]["clothing"].SetString("clothing1");
//删除
doc.RemoveMember("levels");
//将json字符串格式化写入可写路径
rapidjson::StringBuffer buffer;//初始化缓冲区
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);//初始化写入器
doc.Accept(writer);//写入doc
FILE* file = fopen(jsonPath.c_str(), "w+");
if(file)
{
fputs(buffer.GetString(), file);
fclose(file);
}