12

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.

Community
  • 1
  • 1
user3690081
  • 195
  • 2
  • 3
  • 8

3 Answers3

19

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);
hardillb
  • 54,545
  • 11
  • 67
  • 105
  • 2
    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) – salyh Feb 24 '17 at 15:20
7

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)
user5740843
  • 1,540
  • 5
  • 22
  • 42
0

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.

gurma
  • 11
  • 1