2017-05-06 514 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。 这只会使我的代码工作,但不回答我的问题,为什么会发生这种情况。 我仍然期待更好的解决方案。 谢谢大家的帮助!

相关问题