c++ - 如何修复 ZeroMQ 发布者 C++ 中的运行时错误

标签 c++ json

我尝试使用 C++ 在 ZeroMQ 中开发发布者订阅者模型,我从 JSON 文件中提取对象值并将其发送到另一端。

我的订户部分运行良好,但出现任何错误。但是我在发布者部分面临以下错误:(在 if 语句中)

    src/lib_json/json_value.cpp:1136: Json::Value& 
    Json::Value::resolveReference(const char*, bool): Assertion `type_ == 
    nullValue || type_ == objectValue' failed.
    Aborted (core dumped)

这是我的发布者代码:

    #include "jsoncpp/include/json/value.h"
    #include "jsoncpp/include/json/reader.h"
    #include <fstream>
    #include "cppzmq/zmq.hpp"
    #include <string>
    #include <iostream>
    #include <unistd.h>

    using namespace std;

    int main () {
      zmq::context_t context(1);
      zmq::socket_t publisher (context, ZMQ_PUB);
      int sndhwm = 0;
      publisher.setsockopt (ZMQ_SNDHWM, &sndhwm, sizeof (sndhwm));
      publisher.bind("tcp://*:5561");
      const Json::Value p;
      ifstream pub_file("counter.json");
      Json::Reader reader;
      Json::Value root;

      if(pub_file != NULL && reader.parse(pub_file, root)) {
      const Json::Value p = root ["body"]["device_data"]["device_status"];
       }

      string text = p.asString();
      zmq::message_t message(text.size());
      memcpy(message.data() , text.c_str() , text.size());
      zmq_sleep (1);
      publisher.send(message);
      return 0;
     }

最佳答案

const Json::Value p;
...
if(pub_file != NULL && reader.parse(pub_file, root)) {
    const Json::Value p = root ["body"]["device_data"]["device_status"];
}

string text = p.asString();

当您在 if 语句中创建 another p 时,这个新声明的变量仅对条件 {} 代码块的范围。将其更改为对已声明变量 p 的干净赋值:

p = root ["body"]["device_data"]["device_status"];

这会更改外部范围内的变量,而不是在内部范围内声明一个新变量。此外,您应该将变量 const Json::Value p 标记为 not const,以便您可以在条件语句中修改它。

关于c++ - 如何修复 ZeroMQ 发布者 C++ 中的运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46155948/

相关文章:

c++ - 如何将大文件读入 vector 或数组

c++ - 删除空指针

c++ - 如何仅在定义的时间获取事件?

java - Gson:指定类或字段的命名策略

.net - JSON 响应是否应该返回 base64 编码的文件?

c++ - 将文件数据读入二维数组时出现 EXC_BAD_ACCESS

c++ - 函数中的数组初始化

java - 如何使用 Jackson 构建不同对象的 JSON 数组?

javascript - 既然 Express 不带有主体解析器,我如何使用外部中间件解析 JSON?

json - JQ如何从json值打印换行符而不是换行符