How to Send data as JSON objects over to MQTT broker
Asked Answered
T

3

13

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?

I found this article, But its not complete.

Thyratron answered 30/5, 2014 at 5:39 Comment(0)
O
20

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.

 MqttMessage message = new MqttMessage();
 message.setPayload("{foo: bar, lat: 0.23443, long: 12.3453245}".getBytes());
 client.publish("foo", message);
Osbourne answered 30/5, 2014 at 8:8 Comment(1)
You better use String.getBytes(StandardCharsets.UTF_8) because if you not specify the charset it will use your platform defaults which may not UTF-8 (JSON is normally UTF-8)Fissiparous
K
8

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)
Koziarz answered 24/2, 2017 at 15:15 Comment(0)
W
1

If you're using JavaScript, than you can use:

client.publish("foo", JSON.stringify({"foo": bar, "baz": 123})) // on sender side, and

JSON.parse on the receiver end.

Wastebasket answered 24/5, 2021 at 6:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.