如何插入地图或向量来生成一个json字符串(jsoncpp) [英] How to insert a map or vector to generate a json string (jsoncpp)
问题描述
您好,我想做一些简单的lib jsoncpp像这样:
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 );
错误是:error C2679:binary'=':无操作符, 'std :: map< _Kty,_Ty>'
The error is : error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::map<_Kty,_Ty>'
你有想法来解决这个问题吗?我理解json :: value不能接受一个地图,但创建一个json文件应该是,对吧?
非常感谢
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
推荐答案
是的,这不工作,因为 Json: :Value
只接受通用类型或另一个 Json :: Value
。因此,您可以尝试使用 Json :: Value
而不是 std :: map
。
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);
这样做就可以了。如果你真的要使用 std :: map< int,std :: string>
,那么你必须将它转换为 Json :: Value
。这将是(伪未经测试的代码):
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);
这篇关于如何插入地图或向量来生成一个json字符串(jsoncpp)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!