1. 程式人生 > >將json檔案格式化為protobuf

將json檔案格式化為protobuf

#include <fstream>
#include "game_protocol/tools/json_format.h"


template<typename TPBName>
class CConfigJson
{
private:
bool  m_isLoaded;


public:
bool isVailed() { return m_isLoaded; }
public:
CConfigJson()
{
m_pbMessage = NULL;
m_isLoaded = false;
}
~CConfigJson()
{
if (m_pbMessage != NULL)
{
delete m_pbMessage;
}
}


void clear()
{
if (m_pbMessage != NULL)
{
delete m_pbMessage;
m_pbMessage = NULL;
}


m_isLoaded = false;
}


bool load(const char* fileName)
{
if (fileName == NULL)
{
nlwarning("fileName empty");
clear();
return false;
}
std::string outString;


if (!readFileString(fileName, outString))
{
nlwarning("readFile error fileName = [%s]", fileName);
clear();
return false;
}




if (m_isLoaded)
{
m_pbMessage->Clear();
}
else
{
m_pbMessage = new TPBName();
}




if (!google::protobuf::JsonFormat::ParseFromString(outString, m_pbMessage))
{
nlwarning("pb format error!");
clear();
return false;
}


m_isLoaded = true;
return true;
}




TPBName* getConfig() 

if (isVailed() == false)
{
return NULL;
}


return m_pbMessage; 
}


private:
static bool readFileString(const char* fileName, std::string & outString)
{
std::string strfileName = fileName;
std::string filePath = NLMISC::CPath::lookup(strfileName);
std::ifstream inFile(filePath.c_str());
if (!inFile.is_open())
{
nlinfo("no such a file exits %s", fileName);
return false;
}


//只處理 win/linux utf-8 utf-16 utf-32的頭,其他的誰用誰支援
std::string lineStr;
std::vector<std::string> tempStrVector;
if (!getline(inFile, lineStr))
{
nlwarning("the format of the file is error %s", fileName);
return false;
}


static unsigned char charBom[7] = { 0xEF, 0xBB, 0xBF, 0xE, 0x0, 0xFF, 0xFE };


std::size_t found = 0;
for (sint32 i = 0; i < (sint32)lineStr.length(); i++)
{
bool fbom = false;
for (sint32 j = 0; j < sizeof(charBom); j++)
{
if ((unsigned char)lineStr.c_str()[i] == charBom[j])
{
fbom = true;
break;
}
}


if (fbom)
{
found++;
}
else
{
break;
}
}


if (found < lineStr.length())
{
lineStr = lineStr.substr(found);
}
else
{
lineStr.clear();
}




found = lineStr.find_first_of('\r');
if (found != std::string::npos)
{
lineStr.erase(found);
}


outString += lineStr;




while (getline(inFile, lineStr))
{
found = lineStr.find_first_of('\r');
if (found != std::string::npos)
{
lineStr.erase(found);
}


outString += lineStr;
}








return true;
}
TPBName* m_pbMessage;//現new吧?


};


#endif //__CONFIG_JSON_H__