Как я могу добавить строковое сообщение в распределитель документов RapidJson?

Я хочу создать сообщение JSON на С++, используя RapidJson. Итак, в конце я хочу что-то вроде:

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

Чтобы сделать это на С++, я написал этот код:

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);

person Steve Martin    schedule 06.12.2018    source источник


Ответы (1)


Вам нужно добавить #define RAPIDJSON_HAS_STDSTRING 1 перед включением любого заголовка rapidjson, чтобы иметь возможность использовать std::string с rapidjson, или использовать std::string::c_str, чтобы преобразовать вашу строку в const char* и добавить ее в документ.

person Siliace    schedule 06.12.2018
comment
Ура, приятель, спас мой день - person Steve Martin; 06.12.2018
comment
Я знаю, что вы ответили, но есть идеи об этой ошибке? rapidjson::GenericValue<Encoding, Allocator>& rapidjson::GenericValue<Encoding, Allocator>::operator[](const rapidjson::GenericValue<Encoding, SourceAllocator>&) [with SourceAllocator = rapidjson::MemoryPoolAllocator<>; Encoding = rapidjson::UTF8<>; Allocator = rapidjson::MemoryPoolAllocator<>]: Assertion false' не удалось.` - person Steve Martin; 06.12.2018
comment
Я думаю, вы пытаетесь получить доступ к элементу, которого нет в вашем документе. Возможно, в fromScratch["posiiton"] есть опечатка. - person Siliace; 06.12.2018