因为MFC动态链接库项目用第三方json库运行的话会失败,而又不会解决,所以自己写了个构建json字串的类。
class Json {
public:
Json& operator[](const char* key)
{
m_nState = 0;
m_strKey = key;
return *this;
}
Json& operator[](int key)
{
m_nState = 1;
m_nKey = key;
return *this;
}
void operator=(const char* s)
{
m_mapData[m_strKey] = s;
}
void operator=(std::string s)
{
m_mapData[m_strKey] = s;
}
void operator=(Json& j)
{
if (m_nState == 0) {
if (j.m_mapData.size() > 0)
m_mapData[m_strKey] = j.dump();
else if (j.m_mapData2.size() > 0)
m_mapData[m_strKey] = j.dump2();
}
else if (m_nState == 1) {
m_mapData2[m_nKey] = j.dump();
}
}
string dump() {
string s;
for (std::map<std::string, std::string>::iterator it = m_mapData.begin(); it != m_mapData.end(); ++it) {
char* buff;
size_t size;
if (it->first.size() > 0)
{
size = it->first.size() + it->second.size() + 7;
buff = new char[size];
//printf("%s\n", it->second.c_str());
if (it->second.size() > 0 && it->second.c_str()[0] == '\{') {
sprintf_s(buff, size, "\"%s\":%s,", it->first.c_str(), it->second.c_str());
}
else if (it->second.size() > 0 && it->second.c_str()[0] == '\[') {
sprintf_s(buff, size, "\"%s\":%s,", it->first.c_str(), it->second.c_str());
}
else {
sprintf_s(buff, size, "\"%s\":\"%s\",", it->first.c_str(), it->second.c_str());
}
s += buff;
delete[] buff;
}
//std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
size_t size = s.size();
if (size > 0) {
if (s[size - 1] == ','); {
s.erase(size - 1, 1);
s = "{" + s + "}";
}
return s;
}
return "";
}
private:
int m_nState;
std::string m_strKey;
size_t m_nKey;
std::map<std::string, std::string> m_mapData;
std::map<int, std::string> m_mapData2;
string dump2() {
string s;
for (std::map<int, std::string>::iterator it = m_mapData2.begin(); it != m_mapData2.end(); ++it) {
char buff[1024] = "";
//printf("%s\n", it->second.c_str());
if (it->second.size() > 0) {
sprintf_s(buff, 1024, "%s,", it->second.c_str());
s += buff;
}
//std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
size_t size = s.size();
if (size > 0) {
if (s[size - 1] == ','); {
s.erase(size - 1, 1);
s = "[" + s + "]";
}
return s;
}
return "";
}
};