C++ 如何插入映射或向量以生成json字符串(jsoncpp)

C++ 如何插入映射或向量以生成json字符串(jsoncpp),c++,json,vector,map,jsoncpp,C++,Json,Vector,Map,Jsoncpp,嗨,我想用lib jsoncpp做一些简单的事情,如下所示: 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 outp

嗨,我想用lib jsoncpp做一些简单的事情,如下所示:

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 );
std::map mymap;
mymap[0]=“零”;
mymap[1]=“一”;
Json::值根;
根[“teststring”]=“m_teststring”//它起作用了
根[“testMap”]=mymap//它不起作用
Json::StyledWriter编写器;
字符串输出=writer.write(根);
错误为:错误C2679:二进制“=”:未找到接受“std::map”类型的右操作数的运算符

你有办法解决这个问题吗,?我理解json::value不能接受映射,但要创建json文件,它应该是这样的,对吗?
非常感谢

是的,这不起作用,因为
Json::Value
只接受泛型类型或其他
Json::Value
。因此,您可以尝试使用
Json::Value
而不是
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);
这应该可以完成任务。如果您确实必须使用
std::map
,那么您必须首先将其转换为
Json::Value
。这类似于(伪未测试代码):

std::map mymap;
mymap[0]=“零”;
mymap[1]=“一”;
//将std::map转换为Json::Value
Json::Value-jsonMap;
std::map::const_迭代器it=mymap.begin(),end=mymap.end();
for(;it!=end;++it){
jsonMap[std::to_string(it->first)]=it->second;
//^注意:std::to_字符串是C++11
}
Json::值根;
根[“teststring”]=“m_teststring”;
root[“testMap”]=jsonMap;//使用Json::Value而不是mymap
Json::StyledWriter编写器;
常量字符串输出=writer.write(根);

今天我遇到了同样的问题。希望能有帮助


非常感谢,它工作得非常完美,只是在您的回复中进行了更改。首先,通过(*.it)。首先,否则它无法构建。啊,好的。。。我没有测试代码很抱歉,我会更正它;)
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);