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

13,617

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

Solution 2

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

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

Share:
13,617

Related videos on Youtube

Zaibacker
Author by

Zaibacker

Updated on June 04, 2022

Comments

  • Zaibacker
    Zaibacker almost 2 years

    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

  • Zaibacker
    Zaibacker almost 10 years
    Thank you very much, it work perfect, just changing in your response it.first by (*.it).first , otherwise it does not build.
  • AquilaRapax
    AquilaRapax almost 10 years
    Ah ok... i did not test the code Sorry for that, i'll correct it ;)