How to insert a map or vector to generate a json string (jsoncpp)

时光总嘲笑我的痴心妄想 提交于 2019-12-07 16:11:59

问题


Hi I would like to do something easy with the lib jsoncpp like this:

std::map<int,string> mymap;
mymap[0]="zero";
mymap[1]= "one";

Json::Value root;
root["teststring"] = "m_TestString"; //it  works
root["testMap"] = mymap; //it does not work

Json::StyledWriter writer;
string output = writer.write( root );

The error is : error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::map<_Kty,_Ty>'

Do you have an idea to solve this,? I understand that json::value can not accept a map but to create a json file it should be, right? thank you very much


回答1:


Yes, this isn't working, since Json::Value does only accept generic types or another Json::Value. So you could try using a Json::Value instead of std::map.

Json::Value mymap;
mymap["0"] = "zero";
mymap["1"] = "one";

Json::Value root;
root["teststring"] = "m_TestString"; // it works
root["testMap"]    = mymap;          // works now

Json::StyledWriter writer;
const string output = writer.write(root);

This should do the job. If you really have to use a std::map<int, std::string>, then you'll have to convert it to a Json::Value first. This would be something like (pseudo-not-tested-code):

std::map<int, std::string> mymap;
mymap[0] = "zero";
mymap[1] = "one";

// conversion of std::map<int, std::string> to Json::Value
Json::Value jsonMap;
std::map<int, std::string>::const_iterator it = mymap.begin(), end = mymap.end();
for ( ; it != end; ++it) {
    jsonMap[std::to_string(it->first)] = it->second;
    // ^ beware: std::to_string is C++11
}

Json::Value root;
root["teststring"] = "m_TestString";
root["testMap"]    = jsonMap; // use the Json::Value instead of mymap

Json::StyledWriter writer;
const string output = writer.write(root);



回答2:


The same problem comes to me today. hope it helps.

how to write a template converts vector to Json::Value (jsoncpp)



来源:https://stackoverflow.com/questions/24138594/how-to-insert-a-map-or-vector-to-generate-a-json-string-jsoncpp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!