如何将字符串消息添加到RapidJson Document分配器?

时间:2018-12-06 15:17:59

标签: c++ rapidjson

我想使用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);

1 个答案:

答案 0 :(得分:2)

您需要先添加#define RAPIDJSON_HAS_STDSTRING 1,然后再包含任何Rapidjson头,才能将std :: string与Rapidjson一起使用,或者使用std::string::c_str将字符串转换为const char*并将其添加到您的文档。