How to send objects instead of string in mqtt messages?

I am currently using mqtt to communicate between the client and server, and the mqtt publishing method takes the message as bytes. I need to send latitude, longitude, address, etc. In my mqtt post and get them server side. How can i achieve this?

I use the wmqtt client library on the client side (android) and the paho client library on the server side (jsp, servlets).

deviceloc d=new deviceloc(); d.id="1234"; d.add="hyder"; d.lat=17.5; d.lon=78.5; try { ByteArrayOutputStream b = new ByteArrayOutputStream(); ObjectOutputStream o=new ObjectOutputStream(b); o.writeObject(d); byte bytes[]=b.toByteArray(); MqttMessage data=new MqttMessage(bytes); ByteArrayInputStream b1 = new ByteArrayInputStream(data.toString().getBytes()); ObjectInputStream o1 = new ObjectInputStream(b1); Object obj1; try { obj1 = o1.readObject(); deviceloc dd=(deviceloc)obj1; System.out.println(dd.id); System.out.println(dd.add); System.out.println(dd.lat); System.out.println(dd.lon); } catch (ClassNotFoundException e) { e.printStackTrace(); } } catch(IOException e) { e.printStackTrace(); } 

I get an exception using streamcorrupted

0
java android mqtt
source share
1 answer

Serialize your objects in xml strings (either CSV or Json or roll-your-own). Create your message from these lines. Send the message in bytes. The reverse process is on the receiving side.

+1
source share

All Articles