HiveMQ

How to convert Mqtt5Publish payload into JSON

How do I convert Mqtt5Publish.getPayloadAsByteStream() into a properly formatted JSON string?
e.g.
Get a message published like this

'{"SampleData0": "1.2.3", "SampleData1": "4.5.6"}'

Back into the same format when the subscriber obtains it.

Hello @Guiltyfart

Thanks for reaching out.

You can use Mqtt5Publish.getPayloadAsByte() with String to convert into formatted JSON string. Please refer sample code for your reference.

final Mqtt5SubAck subAck = client.subscribeWith()
        .topicFilter("test/topic/a")
        .retainAsPublished(true)                            
        .callback(publish ->
               System.out.println("received message: " + new String(publish.getPayloadAsBytes())))
        .send().join();

I hope this helps.

Kind regards,
Sheetal

1 Like