如何向 RapidJson 文档分配器添加字符串消息?

How can I add a string message to RapidJson Document allocator?

我想使用 RapidJson 在 C++ 中创建 JSON 消息。所以最后,我想要这样的东西:

{"path" : [
    {"position" : {
             "x" : "4",
             "y" : "3"
              },
      "orientation" : {
              "x" : "1"
      }},
    {"position" : {
             "x" : "4",
             "y" : "3"
              },
      "orientation" : {
              "x" : "1"
      }}
    ]
  }

为了在 C++ 中做到这一点,我编写了以下代码:

rapidjson::Document::AllocatorType& allocator = fromScratch.GetAllocator();
std::string ret = "{\"path\" :\" [\"";
for(int i = 0; i<srv.response.plan.poses.size(); i++)
{
    float x = srv.response.plan.poses[i].pose.position.x;
    float y = srv.response.plan.poses[i].pose.position.y;
    float th = srv.response.plan.poses[i].pose.orientation.x;
    std::string pos = "{position:{x:" + std::to_string(x) + ",y:" + std::to_string(y) + "},";
    std::string orient = "{orientation:{x:" + std::to_string(th) + "}}";
    fromScratch.AddMember("position", pos, allocator);
    fromScratch.AddMember("orientation", orient, allocator);
    ret += fromScratch["posiiton"].GetString();
    ret += fromScratch["orientation"].GetString();
    if (i+1 < srv.response.plan.poses.size()) ret += "\",";
    fromScratch.RemoveMember("position");
    fromScratch.RemoveMember("orientation");

}
ret += "]\" }\"";

基本上,srv.response.plan.poses只是一个包含姿势的数组,其中姿势由位置和方向组成,位置有x和y(均为浮点数),与方向相同(只有x)

如您所见,我已将它们转换为字符串并尝试使用 rapidjson 添加成员,但出现此错误:

error: no matching function for call to ‘rapidjson::GenericValue<rapidjson::UTF8<> >::GenericValue(std::__cxx11::basic_string<char>&)’
         GenericValue v(value);

您需要在包含任何 rapidjson header 之前添加 #define RAPIDJSON_HAS_STDSTRING 1 才能将 std::string 与 rapidjson 一起使用或使用 std::string::c_str 将您的字符串转换为 const char* 并将其添加到您的文档中。