How do I convert Mqtt5Publish.getPayloadAsBytes()
into a properly formatted JSON string?
i.e. Get a message published like this:
'{"SampleData0": "1.2.3", "SampleData1": "4.5.6"}'
Back into the same format when the subscriber obtains it.
I'm using the HiveMQTT Client Library in Java.
My Issue was actually caused by some incorrect JSON formatting on the part of the publisher. The publisher client was sending the JSON as:
"{"SampleData0": "1.2.3", "SampleData1": "4.5.6"}"
However this meant that when my subscriber client received the payload and converted it from a byte array into a JSON String the payload would look like this:
{SampleData0: 1.2.3, SampleData1: 4.5.6}
To fix this I had the publisher client send:
'{"SampleData0": "1.2.3", "SampleData1": "4.5.6"}'
Notice the use of single quote, '
, chars rather than double, this escapes the double quote characters, "
, so that they remain present when the byte array is converted back into a JSON, giving this properly formatted JSON string when using new String(mqtt5Publish.getPayloadAsBytes())
{"SampleData0": "1.2.3", "SampleData1": "4.5.6"}