欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C++实现json字符串与map的转换

程序员文章站 2022-06-23 09:11:50
开源资源库 jsoncpp-src-0.5.0.tar.gz:https://sourceforge.net/projects/jsoncpp/ jsoncpp-master.ziphttps://github.com/open-source-parsers/jsoncpp 下面以jsoncpp05 ......

开源资源库

jsoncpp-src-0.5.0.tar.gz:
https://sourceforge.net/projects/jsoncpp/

jsoncpp-master.zip
https://github.com/open-source-parsers/jsoncpp

下面以jsoncpp050版本为例

1:map转化为jsonstr

string map2jsonstr(const map<string,string>& map_info)
{
	json::value jobject;
	for (map<string, string>::const_iterator iter = map_info.begin( ); iter != map_info.end( ); ++iter) 
	{
		jobject[iter->first] = iter->second;
	}
	return jobject.tostyledstring();
}

2:jsonstr转化为map

string itoa_self(int i)
{
	stringstream ss;
	ss << i;
	return ss.str();
}

map<string,string> jsonstr2map(const string& json)
{
	json::reader reader;
	json::value value;
	map<string, string> maps;

	if (json.length() > 0) 
	{
		if (reader.parse(json, value)) 
		{
			json::value::members members = value.getmembernames();
			for (json::value::members::iterator it = members.begin(); it != members.end(); it++) 
			{  
				json::valuetype vt = value[*it].type();
				switch (vt)
				{
				case json::stringvalue:
					{
						maps.insert(pair<string, string>(*it, value[*it].asstring()));
						break;
					}
				case json::intvalue:
					{
						int inttmp = value[*it].asint();
						maps.insert(pair<string, string>(*it, itoa_self(inttmp)));
						break;
					}
				case json::arrayvalue:
					{
						std::string strid;
						for (unsigned int i = 0; i < value[*it].size(); i++)
						{
							strid +=value[*it][i].asstring();
							strid +=",";
						}
						if(!strid.empty())
						{
							strid = strid.substr(0,strid.size()-1);
						}
						maps.insert(pair<string, string>(*it, strid));
						break;
					}
				default:
					{
						break;
					}
				}//end switch
			}//end for
		}//end if
	}

	return maps;
}