我正在使用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]'之後點擊'.'並看看會發生什麼) –