您的位置:首页 > Web前端 > JavaScript

json 解析

2016-07-06 15:26 447 查看
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吧?

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: