Generic message to JSON converter in C++?
Hi, I'm trying to convert a message into a json string.
While it only takes 2 lines in python, this seems more complex in C++.
I have a working example for 1 message type (geometry/msgs/Twist)
void Foo::cmdVelCb(geometry_msgs::msg::Twist::SharedPtr msg)
{
std::string yaml_str = rosidl_generator_traits::to_yaml(*msg);
YAML::Node yaml_node = YAML::Load(yaml_str);
dc_interfaces::msg::StringStamped pub_msg;
nlohmann::json data_json;
data_json["linear"]["x"] = yaml_node["linear"]["x"].as<float>();
data_json["linear"]["y"] = yaml_node["linear"]["y"].as<float>();
data_json["linear"]["z"] = yaml_node["linear"]["z"].as<float>();
data_json["angular"]["x"] = yaml_node["angular"]["x"].as<float>();
data_json["angular"]["y"] = yaml_node["angular"]["y"].as<float>();
data_json["angular"]["z"] = yaml_node["angular"]["z"].as<float>();
}
But now I would like to have a generic way to do it since I will have many more types to handle. Any suggestion?
Thanks
Answer: I could not achieve a generic one but did this using https://github.com/mircodezorzi/tojson
std::string yaml_str = geometry_msgs::msg::to_yaml(*msg);
YAML::Node yaml_node = YAML::Load(yaml_str);
json data_json = tojson::detail::yaml2json(yaml_node);
This still requires to pass geometry_msgs::msg::to_yaml which I would have liked to avoid.