我正在使用Json作为现代C++项目here。我遇到了以下问题。 obj_json
是一个json对象,我想获得obj_json["key"][0][1]
的值,它应该是一个整数值。因此,我写道:错误:超载'stoi(nlohmann :: basic_json <> :: value_type&)'的调用不明确
int id;
id = obj_json["key"][0][1];
我会见了错误说:
terminate called after throwing an instance of 'std::domain_error'
what(): type must be number, but is string
所以我的代码更改为:
int id;
id = std::stoi(obj_json["key"][0][1]);
我收到以下错误:
error: call of overloaded 'stoi(nlohmann::basic_json<>::value_type&)' is ambiguous
In file included from /home/mypath/gcc-5.4.0/include/c++/5.4.0/string:52:0,
from /home/mypath/gcc-5.4.0/include/c++/5.4.0/stdexcept:39,
from /home/mypath/gcc-5.4.0/include/c++/5.4.0/array:38,
from ../json-develop/src/json.hpp:33,
from libnba.cpp:1:
/home/mypath/gcc-5.4.0/include/c++/5.4.0/bits/basic_string.h:5258:3: note: candidate: int std::__cxx11::stoi(const string&, std::size_t*, int)
stoi(const string& __str, size_t* __idx = 0, int __base = 10)
^
/home/mypath/gcc-5.4.0/include/c++/5.4.0/bits/basic_string.h:5361:3: note: candidate: int std::__cxx11::stoi(const wstring&, std::size_t*, int)
stoi(const wstring& __str, size_t* __idx = 0, int __base = 10)
我对此感到困惑。如第一条错误消息所示,obj_json["key"][0][1]
是string
。但在第二个错误消息中,为什么会发生错误? 我还打印出对象的类型,使用下面的代码:
cout << typeid(obj_json["key"][0][1]).name() << endl;
打印的类型是
N8nlohmann10basic_jsonISt3mapSt6vectorNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEblmdSaEE
我完全糊涂了...... 如何解决这个问题? 谢谢你帮助我!
“超载呼叫”错误后,应该有一个可行的功能列表。请编辑您的问题以添加它们。 – aschepler
@aschepler我添加了所有的错误信息。谢谢。 – pfc
尝试'std :: stoi(std :: string(obj_json [“key”] [0] [1]))',错误信息表明json结果可以转换为'string'或'wstring',所以你必须选择。可能有一个成员函数可以使用,而不是显式强制转换(如果你在IDE中,在'[1]'之后点击'.'并看看会发生什么) –