快速JSON如何使用字符串变量查询对象

RapidJSON how to query an object using a string variable

本文关键字:变量 查询 对象 字符串 何使用 JSON 快速      更新时间:2023-10-16

当我尝试使用字符串变量查询对象时,我收到错误,但当我直接使用字符串时则不然。

杰森: {"x": "hello"}

这有效:

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

这不起作用:

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

我收到此错误:

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

我做错了什么?

尝试

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

似乎运算符不是针对 std::string 重载,而是针对 C 字符串。

(c_str成员函数的参考)