简体   繁体   English

RapidJSON如何使用字符串变量查询对象

[英]RapidJSON how to query an object using a string variable

I'm getting an error when I try to query an object using a string variable, but not when I directly use a string. 当我尝试使用字符串变量查询对象时出现错误,但是当我直接使用字符串时却出现错误。

JSON: {"x": "hello"} JSON: {"x": "hello"}

This works: 这有效:

std::cout << document["x"].GetString();

This doesn't work: 这不起作用:

std::string s = "x";
std::cout << document[s].GetString();

I'm getting this error: 我收到此错误:

error: no viable overloaded operator[] for type 'rapidjson::Document'
  (aka 'GenericDocument<UTF8<> >')
std::cout << document[s].GetString();
                ~~~~~^~
note: candidate function not viable: no known conversion from 'std::string'
  (aka 'basic_string<char, char_traits<char>, allocator<char> >') to 'SizeType' 
(aka 'unsigned int') for 1st argument

What am I doing wrong? 我究竟做错了什么?

Try 尝试

std::cout << document[s.c_str()].GetString();

It seems the operator was not overloaded for a std::string but for a C-string. 似乎操作符不是为std :: string重载,而是为C字符串重载。

(Reference for the c_str member function) (有关c_str成员函数的参考)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM