I want to populate Java pojo class with mqtt message payload in a spring mvc application. My code is :
String messagePayload = (String) message.getPayload();
ObjectMapper objectMapper= new ObjectMapper();
Test test = null;
try {
test = objectMapper.readValue(messagePayload, Test.class);
} catch (IOException e) {
e.printStackTrace();
return;
}
MQTT MessagePayload is {"name":"abc","age": 32}
, but when It get converted into String in variable messagePayload, it shows like {name:abc,age:32}. You see, dropping all double quotes. This when goes to try block throws an error
com.fasterxml.jackson.core.JsonParseException: Unexpected character ('n' (code 110)): was expecting double-quote to start field name
at [Source: (String)"{name:abc,age:34}"; line: 1, column: 3]
I need help in converting the MQTT message into the Java POJO class. Is there another way to do it? Or how can I correct my existing codes?
CodePudding user response:
MqttMessage.getPayload() returns a byte[]. To convert this into a String object you should use new String(message.getPayload())
CodePudding user response:
I resolved this. Actually, I was passing the message from cmd (mosquitto is installed in my windows) like
mosquitto_pub -t whatTopic -m "{"name":abc, "age":32}".
In this message was coming in spring mvc application like
{name:abc,age:32}. Thus it could not be deserialized into object with Jackson or Gson libraries.
However, when I send the same message with tool MQTTLens the message was coming completely like
{"name":abc, "age":32}
Now, this can be deserialized into a java object.
So, I now assume that from the command prompt only string should be sent. If one wants to test an application with JSON format like messages, test with a tool like MQTTLens.