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

别等时光非礼了梦想. 提交于 2019-12-06 01:56:04

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);
tryer3000

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

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

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