Home > Software engineering >  BOOST request sending JSON data
BOOST request sending JSON data

Time:05-19

I want to transfer json data into request of json boost in cpp.

If i take json in boost


int outer=2;

value data = {
        {"dia",outer},
        {"sleep_time_in_s",0.1}
    };

request.body()=data;

like above i want to send data from boost client to server , but it's through error is any one understand below error suggest me .

error C2679: binary '=': no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)

C:\Boost\boost/beast/core/multi_buffer.hpp(360,25): message : could be 'boost::beast::basic_multi_buffer<std::allocator<char>> &boost::beast::basic_multi_buffer<std::allocator<char>>::operator =(const boost::beast::basic_multi_buffer<std::allocator<char>> &)'

2>C:\Boost\boost/beast/core/multi_buffer.hpp(345,5): message : or       'boost::beast::basic_multi_buffer<std::allocator<char>> &boost::beast::basic_multi_buffer<std::allocator<char>>::operator =(boost::beast::basic_multi_buffer<std::allocator<char>> &&)'

2>C:\Development\qa-cal\sysqa_cpp\src\guiClient\boostHttpClient.cpp(90,31): message : while trying to match the argument list '(boost::beast::basic_multi_buffer<std::allocator<char>>, std::string)'

CodePudding user response:

C is strongly typed. You cannot assign a json::value to something else. In this case your body() is likely something like std::string.

Assuming that value is boost::json::value you should write something like:

request.body() = serialize(data);

Where boost::json::serialize serializes the data value into string representation.

Live Demo

#include <boost/beast.hpp>
#include <boost/json.hpp>
#include <boost/json/src.hpp>
#include <iostream>
namespace http = boost::beast::http;

int main() {
    using boost::json::value;
    http::request<http::string_body> request(
            http::verb::post, "/some/api", 11);

    {
        int outer = 2;
        value data  = {
            {"dia", outer},
            {"sleep_time_in_s", 0.1},
        };
        request.body() = serialize(data);
    }

    request.prepare_payload();

    std::cout << request;
}

Prints

POST /some/api HTTP/1.1
Content-Length: 32
{"dia":2,"sleep_time_in_s":1E-1}
  • Related