首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我想使用nlohmann:json解析带有msgpack数据的boost::beast::flat_buffer。

我想使用nlohmann:json解析带有msgpack数据的boost::beast::flat_buffer。
EN

Stack Overflow用户
提问于 2021-08-19 13:46:42
回答 1查看 771关注 0票数 3

因此,我使用boost::beast作为WebSocket服务器。我希望接收一条二进制消息并使用nlohmann::json解析它。不过,我收到了一条错误消息:

三个重载都不能转换参数"nlohmann::detail::input_adapter“。

以下是一些代码:

代码语言:javascript
复制
        boost::beast::flat_buffer buffer;
        ws.read(buffer);
        if (!ws.got_text()) {
            ws.text(false);
            json request = json::from_msgpack(msgpack);
            ws.write( json::to_msgpack(request) ); // echo request back
        }

如果我尝试将静态转换转换为std::向量,则得到: E0312 / no适当的用户定义转换。

代码语言:javascript
复制
        boost::beast::flat_buffer buffer;
        ws.read(buffer);
        if (!ws.got_text()) {
            ws.text(false);
            boost::asio::mutable_buffer req = buffer.data();
            //unsigned char* req2 = static_cast<unsigned char*>(req);                     // does not work
            //std::vector<std::uint8_t> req2 = static_cast<std::vector<std::uint8_t>>(req); // does not work
            json request = json::from_msgpack(buffer.data());
            ws.write(boost::asio::buffer(json::to_msgpack(request)));
        }

如何从缓冲区中获取二进制数据,以便nkohman::json能够解析它?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-19 15:07:09

您可以使用基于迭代器的重载:

在编译器资源管理器上直播

代码语言:javascript
复制
#include <boost/asio/buffers_iterator.hpp>
#include <boost/beast.hpp>
#include <boost/beast/websocket.hpp>
#include <nlohmann/json.hpp>

int main() {
    using nlohmann::json;
    using boost::asio::ip::tcp;
    boost::asio::io_context io;
    boost::beast::websocket::stream<tcp::socket> ws(io);

    boost::beast::flat_buffer buffer;
    ws.read(buffer);
    if (!ws.got_text()) {
        ws.text(false);

        auto req     = buffer.data();
        auto request = json::from_msgpack(buffers_begin(req), buffers_end(req));

        ws.write(boost::asio::buffer(json::to_msgpack(request)));
    }
}

ADL会找到合适的过载(例如,boost::asio::buffers_begin)

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68849076

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档