Robotics StackExchange | Archived questions

How to send data in Json format using service client in c++ code

Hi ,

How data send in Json format using service client ROS in c++ code(using srv file).

Clientsrv.srv
op
topic
type
---
responce

For example :

{ "op": "subscribe", "topic": "/cmdvel", "type": "geometrymsgs/Twist" }

Thanks.

Asked by can-43811 on 2017-04-24 07:26:11 UTC

Comments

You can put json into a string. Or do you mean make the entire message into json, and use it outside of ros with for example a web server that uses json?

Asked by lucasw on 2017-04-24 10:56:04 UTC

yes entire request format should be in json format and same needs to be published so that other node can subscribe the same.

Asked by can-43811 on 2017-04-24 20:06:00 UTC

Answers

Am not so sure what you want to do, but I can tell you C++ and Json... hummm

you can use a lib called rapid json and generate the json you need appending key-values as it were a dictionary

here an example:

#include <iostream>
#include <string>

#include <rapidjson\document.h>
#include <rapidjson\writer.h>
#include <rapidjson\stringbuffer.h>

void output(const rapidjson::Document& document)
{

    std::string strOp = document["op"].GetString();
    std::string ret = "{\"op\":\"" + strOp;

    std::string strTopic = document["topic"].GetString();
    ret += "\", \"topic\":\"" + strTopic;

    std::string strType = document["type"].GetString();
    ret += "\", \"type\":\"" + strType + "\"}";


    std::cout << "json" << std::endl;
    std::cout << ret << std::endl;
    //{ "op": "subscribe", "topic" : "/cmd_vel", "type" : "geometry_msgs/Twist" }
}

int main(int argC, char** argV)
{
    std::cout << "ROS" << std::endl;
    rapidjson::Document fromScratch;

    fromScratch.SetObject();
    rapidjson::Document::AllocatorType& allocator = fromScratch.GetAllocator();

    fromScratch.AddMember("op", "subscribe", allocator);
    fromScratch.AddMember("topic", "/cmd_vel", allocator);
    fromScratch.AddMember("type", "geometry_msgs/Twist", allocator);

    output(fromScratch);

    getchar();
    return 0;
}

The output will look like: image description

Asked by ΦXocę 웃 Пepeúpa ツ on 2017-04-24 11:42:51 UTC

Comments

Sure i will form the json string in above format and publish through service client. usually i need 10 this kind of strings . In this case i need to use array of strings.

Asked by can-43811 on 2017-04-24 20:08:08 UTC

JSON can represent arrays too, why not do it all in one string?

Asked by PeteBlackerThe3rd on 2018-07-20 00:51:53 UTC