I want to create a JSON message in C++ using RapidJson. So at the end, I want something like:
{"path" : [
{"position" : {
"x" : "4",
"y" : "3"
},
"orientation" : {
"x" : "1"
}},
{"position" : {
"x" : "4",
"y" : "3"
},
"orientation" : {
"x" : "1"
}}
]
}
In order to do that in C++, I have written this code:
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 += "]\" }\"";
Basically, srv.response.plan.poses is just an array consisting poses, where poses consists of position and orientation and position has x and y (both floats), same with orientation (only x)
As you can see, I have converted them to strings and tried to add member using rapidjson but I am getting this error:
error: no matching function for call to ‘rapidjson::GenericValue<rapidjson::UTF8<> >::GenericValue(std::__cxx11::basic_string<char>&)’
GenericValue v(value);
You need to add #define RAPIDJSON_HAS_STDSTRING 1
before including any rapidjson header to be able to use std::string with rapidjson or use std::string::c_str
to convert your string to a const char*
and add it in your document.