RadpidJson使用类JsonUtils分享

在网上找到的一个utils类,增加了一些函数定义,以及其他修改,但是最终因为部分函数未定义,修改起来工作量太大暂时没有使用,这里先保留一下修改进度,备份。

头文件:

//*******************************  
// Json Parse  
// Created by Simon on 10/29/2015
// Edited by autumoon on 01/05/2022  
//*******************************  
  
#ifndef _JSON_UTILS_H_  
#define  _JSON_UTILS_H_  
  
#include <iostream>  
#include <string>  
#include "rapidjson.h"  
#include "document.h"  
#include "writer.h"  
#include "stringbuffer.h"  
#include "prettywriter.h"
  
using namespace std;  
using namespace rapidjson;  
  
// Basic Check;  
#define json_check_is_bool(value, strKey) (value.HasMember(strKey) && value[strKey].IsBool())  
#define json_check_is_string(value, strKey) (value.HasMember(strKey) && value[strKey].IsString())  
#define json_check_is_int32(value, strKey) (value.HasMember(strKey) && value[strKey].IsInt())  
#define json_check_is_uint32(value, strKey) (value.HasMember(strKey) && value[strKey].IsUint())  
#define json_check_is_int64(value, strKey) (value.HasMember(strKey) && value[strKey].IsInt64())  
#define json_check_is_uint64(value, strKey) (value.HasMember(strKey) && value[strKey].IsUint64())  
#define json_check_is_double(value, strKey) (value.HasMember(strKey) && value[strKey].IsDouble())  
#define json_check_is_number(value, strKey) (value.HasMember(strKey) && value[strKey].IsNumber())  
#define json_check_is_array(value, strKey) (value.HasMember(strKey) && value[strKey].IsArray())  
#define json_check_is_object(value, strKey) (value.HasMember(strKey) && value[strKey].IsObject())  

const int ENCRYPTION = 0;  
  
class JsonUtils
{  
private:  
    JsonUtils();  
    ~JsonUtils();  
  
    static JsonUtils* _self;  
  
    map<std::string, rapidjson::Document*> _docBuffer;  
  
public:  
    static JsonUtils* getInstance();  
    void deleteInstance();  
  
    //-----------UserData-Method-Begin-----------;
	string getStringFromFile(string filePath);
  
    // Type 1 : writable path, Type : 0 resource path;  
    void loadJson(string filename, bool isWritable = true);  
    void parseJson(string filename, string jsonBuffer);  
    void writeJson(string filename);  
    void setValue(string filename, string key, rapidjson::Value& value, bool save = false);  
    void saveJson(rapidjson::Document* doc, const std::string &fileName, bool prettyFlag = true, bool Asynchronous = false);  
    void saveJson(const std::string& filename, bool prettyFlag = true, bool Asynchronous = false);  
    void unloadJson(string filename);  
  
    void setIntegerForKey(string key, int value, string filename, bool save = false);  
    int getIntegerForKey(string key, string filename);  
    void setBooleanForKey(string key, bool value, string filename, bool save = false);  
    bool getBooleanForKey(string key, string filename);  
    void setDoubleForKey(string key, float value, string filename, bool save = false);  
    float getDoubleForKey(string key, string filename);  
    void setStringForKey(string key, string value, string filename, bool save = false);  
    string getStringForKey(string key, string filename);

    rapidjson::Document* getDoc(string filename);  
    rapidjson::Value& getValue(string filename, string key);  

    void example();  
    //--------------UserData-Method-End-------------  
};  
  
#endif  //_JSON_UTILS_H_  

 

//*******************************  
// Json Parse  
// Created by Simon on 10/29/2015
// Edited by autumoon on 01/05/2022  
//*******************************  
  
#include "JsonUtils.h"  
  
JsonUtils* JsonUtils::_self = nullptr;  
  
JsonUtils::JsonUtils()  
{  
    _docBuffer.clear();  
}  
  
JsonUtils::~JsonUtils()  
{
}  
  
JsonUtils* JsonUtils::getInstance()  
{  
    if (!_self)  
    {  
        _self = new JsonUtils();  
    }  
    return _self;  
}  
  
void JsonUtils::deleteInstance()  
{  
    if (_self)  
    {  
        delete(_self);  
    }  
    _self = nullptr;  
}  
  
std::string JsonUtils::getStringFromFile(string filePath)
{
	using namespace rapidjson;

	std::ifstream ifs(szJsonPath);

	if (!ifs.is_open() )
	{
		return "";
	}

	IStreamWrapper isw(ifs);

	Document doc;

	doc.ParseStream( isw );
	StringBuffer buffer;

	Writer<StringBuffer> writer(buffer);
	doc.Accept( writer );

	if (doc.HasParseError())
	{
		return "";
	}

	sJsonStr = buffer.GetString();

	return sJsonStr;
}

void JsonUtils::loadJson(string filename, bool isWritable)  
{  
    string path = "";  
    if (isWritable)  
    {  
        path = FileUtils::getInstance()->getWritablePath().append(filename);  
        assert(path!="");  
    }  
    else  
    {  
        path = REF_PATH + filename;  
    }  
  
    if (!FileUtils::getInstance()->isFileExist(path))  
    {  
        File_Not_Exist(filename.c_str(), "JsonUtils::loadJson");  
        writeJson(filename);  
    }  
  
    string jsonBuffer = FileUtils::getInstance()->getStringFromFile(path);  
    assert(jsonBuffer != "");  
    parseJson(filename, jsonBuffer);  
}  
  
void JsonUtils::parseJson(string filename, string jsonBuffer)  
{  
    rapidjson::Document* doc = new rapidjson::Document();  
    doc->Parse<rapidjson::kParseDefaultFlags>(jsonBuffer.c_str());  
    assert(doc->IsObject());  
    _docBuffer[filename] = doc;  
}  
  
void JsonUtils::writeJson(string filename)  
{  
    string value = filename + " data";  
    rapidjson::Document* doc = new rapidjson::Document();  
    rapidjson::Document::AllocatorType& allocator = doc->GetAllocator();  
    doc->SetObject();  
    doc->AddMember("description", StringRef(value.c_str()), allocator);  
    saveJson(doc, filename);  
}  
  
void JsonUtils::setValue(string filename, string key, rapidjson::Value& value, bool save)  
{  
    rapidjson::Document* doc = _docBuffer[filename];  
    rapidjson::Document::AllocatorType& allocator = doc->GetAllocator();  
    assert(doc->IsObject());  
    rapidjson::Value& var = *doc;  
    if (doc->HasMember(key.c_str()))  
    {  
        var[key.c_str()] = value;  
        if (save)  
            saveJson(doc, filename);  
    }  
    else  
    {  
        doc->AddMember(StringRef(key.c_str()), value, allocator);  
  
        saveJson(doc, filename);  
        string name = filename + ".json";  
        string jsonBuffer = FileUtils::getInstance()->getStringFromFile(FileUtils::getInstance()->getWritablePath().append(name));  
        assert(jsonBuffer != "");  
        parseJson(filename, jsonBuffer);  
    }  
}  
  
void JsonUtils::saveJson(rapidjson::Document* doc, const std::string &fileName, bool prettyFlag, bool Asynchronous)  
{  
    StringBuffer buffer;  
    buffer.Clear();  
    if (prettyFlag)  
    {  
        rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);  
        //writer.SetIndent(' ', 2);  
        doc->Accept(writer);  
    }  
    else  
    {  
        rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);  
        doc->Accept(writer);  
    }  
  
    std::function<void(std::string, std::string)> saveHandler = [](std::string str, std::string fName)  
    {  
#if ENCRYPTION  
        std::string tag = fName;  
        for (int i = 0; i < str.size(); i++)  
            str[i] ^= tag[i % tag.size()];  
#endif  
        std::string filepath = FileUtils::getInstance()->getWritablePath().append(fName);  
        FILE *fp = fopen(filepath.c_str(), "wb");  
        //fputs(str.c_str(), fp);  
        fwrite(str.c_str(), 1, str.size(), fp);  
  
#if ENCRYPTION  
        string tagStr = tag;  
        for (int i = 0; i < tag.size(); i++)  
            tagStr[i] ^= tag[tag.size() - 1 - i];  
        fwrite(tagStr.c_str(), 1, tagStr.size(), fp);  
#endif  
        fclose(fp);  
    };  
  
    if (Asynchronous)  
    {  
        std::thread save(saveHandler, std::string(buffer.GetString(), buffer.GetSize()), fileName);  
        save.detach();  
    }  
    else  
    {  
        saveHandler(std::string(buffer.GetString(), buffer.GetSize()), fileName);  
    }  
}  
  
void JsonUtils::saveJson(const std::string& filename, bool prettyFlag /*= true*/, bool Asynchronous /*= false*/)  
{  
    saveJson(_docBuffer[filename], filename, prettyFlag, Asynchronous);  
}  
  
void JsonUtils::unloadJson(string filename)  
{  
    map<string, rapidjson::Document*>::iterator iter;  
    iter = _docBuffer.find(filename);  
    if (iter != _docBuffer.end())  
    {  
        _docBuffer.erase(iter);  
    }  
}  
  
void JsonUtils::setIntegerForKey(string key, int value, string filename, bool save)  
{  
    rapidjson::Document* doc = _docBuffer[filename];  
    rapidjson::Document::AllocatorType& allocator = doc->GetAllocator();  
    if (json_check_is_int32((*doc), key.c_str()))  
    {  
        (*doc)[key.c_str()].SetInt(value);  
        if (save)  
            saveJson(doc, filename);  
    }  
    else  
    {  
        doc->AddMember(StringRef(key.c_str()), value, allocator);  
  
        saveJson(doc, filename);  
        string name = filename + ".json";  
        string jsonBuffer = FileUtils::getInstance()->getStringFromFile(FileUtils::getInstance()->getWritablePath().append(name));  
        assert(jsonBuffer != "");  
        parseJson(filename, jsonBuffer);  
    }  
}  
  
int JsonUtils::getIntegerForKey(string key, string filename)  
{  
    rapidjson::Document* doc = _docBuffer[filename];  
    assert(doc);  
    if (json_check_is_int32((*doc), key.c_str()))  
    {  
        return (*doc)[key.c_str()].GetInt();  
    }  
    return 0;  
}  
  
void JsonUtils::setBooleanForKey(string key, bool value, string filename, bool save)  
{  
    rapidjson::Document* doc = _docBuffer[filename];  
    rapidjson::Document::AllocatorType& allocator = doc->GetAllocator();  
    rapidjson::Value& var = *doc;  
    if (json_check_is_bool(var, key.c_str()))  
    {  
        var[key.c_str()].SetBool(value);  
        if (save)  
            saveJson(doc, filename);  
    }  
    else  
    {  
        doc->AddMember(StringRef(key.c_str()), value, allocator);  
  
        saveJson(doc, filename);  
        string name = filename + ".json";  
        string jsonBuffer = FileUtils::getInstance()->getStringFromFile(FileUtils::getInstance()->getWritablePath().append(name));  
        assert(jsonBuffer != "");  
        parseJson(filename, jsonBuffer);  
    }  
}  
  
bool JsonUtils::getBooleanForKey(string key, string filename)  
{  
    if (_docBuffer[filename] && _docBuffer[filename]->HasMember(key.c_str()))  
    {  
        return (*_docBuffer[filename])[key.c_str()].GetBool();  
    }  
    return false;  
}  
  
void JsonUtils::setDoubleForKey(string key, float value, string filename, bool save)  
{  
    rapidjson::Document* doc = _docBuffer[filename];  
    rapidjson::Document::AllocatorType& allocator = doc->GetAllocator();  
    rapidjson::Value& var = *doc;  
    string floatStr = __String::createWithFormat("%.2f", value)->getCString();  
    if (json_check_is_string(var, key.c_str()))  
    {  
        var[key.c_str()].SetString(StringRef(floatStr.c_str()), allocator);  
        if (save)  
            saveJson(doc, filename);  
    }  
    else  
    {  
        doc->AddMember(StringRef(key.c_str()), StringRef(floatStr.c_str()), allocator);  
        saveJson(doc, filename);  
        string name = filename + ".json";  
        string jsonBuffer = FileUtils::getInstance()->getStringFromFile(FileUtils::getInstance()->getWritablePath().append(name));  
        assert(jsonBuffer != "");  
        parseJson(filename, jsonBuffer);  
    }  
}  
  
float JsonUtils::getDoubleForKey(string key, string filename)  
{  
    if (_docBuffer[filename] && _docBuffer[filename]->HasMember(key.c_str()))  
    {  
        return atof(((*_docBuffer[filename])[key.c_str()].GetString()));  
    }  
    return 0.0f;  
}  
  
void JsonUtils::setStringForKey(string key, string value, string filename, bool save)  
{  
    rapidjson::Document* doc = _docBuffer[filename];  
    rapidjson::Document::AllocatorType& allocator = doc->GetAllocator();  
    rapidjson::Value& var = *doc;  
    if (json_check_is_string(var, key.c_str()))  
    {  
        var[key.c_str()].SetString(StringRef(value.c_str()), allocator);  
        if (save)  
            saveJson(doc, filename);  
    }  
    else  
    {  
        doc->AddMember(StringRef(key.c_str()), StringRef(value.c_str()), allocator);  
  
        saveJson(doc, filename);  
        string name = filename + ".json";  
        string jsonBuffer = FileUtils::getInstance()->getStringFromFile(FileUtils::getInstance()->getWritablePath().append(name));  
        assert(jsonBuffer != "");  
        parseJson(filename, jsonBuffer);  
    }  
}  
  
std::string JsonUtils::getStringForKey(string key, string filename)  
{  
    if (_docBuffer[filename] && _docBuffer[filename]->HasMember(key.c_str()))  
    {  
        return (*_docBuffer[filename])[key.c_str()].GetString();  
    }  
    return "";  
}  
  
rapidjson::Document* JsonUtils::getDoc(string filename)  
{  
    if (_docBuffer[filename])  
    {  
        return _docBuffer[filename];  
    }  
    return nullptr;  
}  
  
rapidjson::Value& JsonUtils::getValue(string filename, string key)  
{  
    if (_docBuffer[filename] && _docBuffer[filename]->HasMember(key.c_str()))  
    {  
        return (*_docBuffer[filename])[key.c_str()];  
    }  
}  
  
void JsonUtils::example(const char* szJsonPath1, const char* szJsonPath2)  
{  
    JsonUtils::getInstance()->loadJson(szJsonPath1);  
    JsonUtils::getInstance()->loadJson(szJsonPath2);  
  
    int num = 100;  
    string key1 = "aaa";  
    string key2 = "bb";  
    string key3 = "c";  
    string key4 = "d";  
    JsonUtils::getInstance()->setIntegerForKey(key1, num, szJsonPath1);  
    JsonUtils::getInstance()->setIntegerForKey(key1, num, szJsonPath2);  
    int temp = JsonUtils::getInstance()->getIntegerForKey(key1, szJsonPath1);  
    int temp2 = JsonUtils::getInstance()->getIntegerForKey(key1, szJsonPath2);  
    CCLOG("%d  %d ", temp, temp2);  
  
    JsonUtils::getInstance()->setStringForKey(key4, "dddddddd", szJsonPath1);  
    string temp9 = JsonUtils::getInstance()->getStringForKey(key4, szJsonPath1);  
    CCLOG("%s", temp9.c_str());  
  
    JsonUtils::getInstance()->setStringForKey(key4, "ffffffff", szJsonPath1);  
    string temo0 = JsonUtils::getInstance()->getStringForKey(key4, szJsonPath1);  
    CCLOG("%s", temo0.c_str());  
  
    JsonUtils::getInstance()->setBooleanForKey(key2, true, szJsonPath1);  
    JsonUtils::getInstance()->setBooleanForKey(key2, true, szJsonPath2);  
    bool temp32 = JsonUtils::getInstance()->getBooleanForKey(key2, szJsonPath1);  
    bool temp3 = JsonUtils::getInstance()->getBooleanForKey(key2, szJsonPath2);  
      
    JsonUtils::getInstance()->setDoubleForKey(key3, 1.56f, szJsonPath1);  
    double temp6 = JsonUtils::getInstance()->getDoubleForKey(key3, szJsonPath1);  
    CCLOG("%f     ", temp6);  
  
    JsonUtils::getInstance()->saveJson(szJsonPath1);  
  
    // Value Methods;  
    rapidjson::Value cache;  
    cache.SetInt(12220);  
    JsonUtils::getInstance()->setValue(szJsonPath1, "qwer", cache);  
  
    cache.SetBool(false);  
    JsonUtils::getInstance()->setValue(szJsonPath1, "bool", cache);  
  
    cache.SetDouble(1.9966f);  
    JsonUtils::getInstance()->setValue(szJsonPath1, "float", cache);  
  
    cache.SetString("gggg");  
    JsonUtils::getInstance()->setValue(szJsonPath1, "ConstString", cache);  
  
    string hello = "dd";  
    cache.SetString(StringRef(hello.c_str()));  
    JsonUtils::getInstance()->setValue(szJsonPath1, "CopyString", cache);  
  
    rapidjson::Document* please = JsonUtils::getInstance()->getDoc(szJsonPath1);  
    CCLOG("%s", (*please)["d"].GetString());  
  
    // Other Path Files;  
    JsonUtils::getInstance()->loadJson("data.json", false);  
    string data = JsonUtils::getInstance()->getStringForKey(key4, "data");  
    CCLOG("data from ref/data %s", data.c_str());  
}  
  
//_EOF_

 

上一篇:【数学】乘法逆元


下一篇:Codeforces 698F - Coprime Permutation(找性质)