如何将数据作为 JSON 对象发送到 MQTT 代理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23947779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:19:52  来源:igfitidea点击:

How to Send data as JSON objects over to MQTT broker

jsonmqttpaho

提问by user3690081

I'm using eclipse paho client on ubuntu and trying to send latitude, longitude and timestamp information as JSON format to the MQTT broker. How do I do that?

我在 ubuntu 上使用 eclipse paho 客户端,并尝试将纬度、经度和时间戳信息作为 JSON 格式发送到 MQTT 代理。我怎么做?

I found this article, But its not complete.

我找到了这篇文章,但它并不完整。

回答by hardillb

You just need to create your JSON object as a string then call getBytes() on that string to get the byte array to use as your payload in the message.

您只需将 JSON 对象创建为字符串,然后对该字符串调用 getBytes() 以获取字节数组以用作消息中的有效负载。

 MqttMessage message = new MqttMessage();
 message.setPayload("{foo: bar, lat: 0.23443, long: 12.3453245}".getBytes());
 client.publish("foo", message);

回答by user5740843

I don't know about that, but I use his:

我不知道,但我使用他的:

#!/usr/bin/python
import json
import paho.mqtt.client as mqtt


send_msg = {
        'data_to_send': variable1,
        'also_send_this': variable2
}

client.publish("topic", payload=json.dumps(send_msg), qos=2, retain=False)