2017-05-06 513 views
0

我正在使用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 

我完全糊塗了...... 如何解決這個問題? 謝謝你幫助我!

+0

「超載呼叫」錯誤後,應該有一個可行的功能列表。請編輯您的問題以添加它們。 – aschepler

+0

@aschepler我添加了所有的錯誤信息。謝謝。 – pfc

+0

嘗試'std :: stoi(std :: string(obj_json [「key」] [0] [1]))',錯誤信息表明json結果可以轉換爲'string'或'wstring',所以你必須選擇。可能有一個成員函數可以使用,而不是顯式強制轉換(如果你在IDE中,在'[1]'之後點擊'.'並看看會發生什麼) –

回答

3

你的問題是obj_json["key"][0][1]不是字符串。它的類型是:nlohmann::basic_json<>::value_type。你應該尋找圖書館,並檢查什麼是nlohmann::basic_json<>::value_type,以及如何將其轉換爲數字。

0

我找到了一個有用的答案here。在這個問題的答案中,有人說basic_json可以轉換爲charstd::string,這使得編譯器不知道對象的類型。我不知道這是否是我自己問題的原因。但是,下面的解決方案適用於我:

int id; 
str temp_str_val; 
temp_str_val = obj_json["key"][0][1]; 
id = stoi(temp_str_val); 

也就是說,聲明一個變量string和第一值複製到它。然後在string變量上致電stoi。 這隻會使我的代碼工作,但不回答我的問題,爲什麼會發生這種情況。 我仍然期待更好的解決方案。 謝謝大家的幫助!

相關問題