![](/img/trans.png)
[英]How to read json file using rapidjson and output to std::string?
[英]Read JSON with RapidJSON
使用 RapidJSON,我可以通过以下方式读取本地 json 文件:
std::ifstream ifs { R"(/home//am_v2.json)" };
IStreamWrapper isw { ifs };
Document doc {};
doc.ParseStream( isw );
但是,我想读取从以下位置收到的变量:
auto msg = mqttClient->consume_message();
内容由msg->to.string()
显示
但是,我无法使用以下方法读取此内容:
std::ifstream ifs { msg };
有什么线索吗?
这里有一个更完整的代码:
void MqttApplication::send()
{
try {
mqttClient->start_consuming();
mqttClient->subscribe(TOPIC, QOS)->wait();
}
catch (const mqtt::exception& exc) {
cerr << exc.what() << endl;
return;
}
while (true) {
auto msg = mqttClient->consume_message();
if (!msg) {
if (!mqttClient->is_connected()) {
cout << "MQTT: mqtt_application lost connection. Attempting reconnect" << endl;
if (mqttTryReconnect(*mqttClient)) {
mqttClient->subscribe(TOPIC, QOS);
cout << "MQTT: mqtt_application reconnected" << endl;
continue;
}
else {
cout << "MQTT: mqtt_application reconnect failed." << endl;
}
}
else {
cout << "MQTT: mqtt_application an error occurred retrieving messages." << endl;
}
break;
}
if (msg->get_topic() == "command" &&
msg->to_string() == "exit") {
cout << "Exit command received" << endl;
break;
}
cout << msg->get_topic() << ": " << msg->to_string() << endl;
Document doc;
doc.Parse(msg->to.string());
}
}
谢谢
首先,确保你
#define RAPIDJSON_HAS_STDSTRING 1
在包含 Rapidjson 标头之前。
解析来自 mqtt 的消息内容非常简单:
Document doc;
doc.Parse(msg->to.string());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.