How to insert a map or vector to generate a json s

2019-05-11 12:54发布

问题:

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)