Skip to content
Advertisement

Message contains escape character in the message sent to MQ and cause exception when converting to JSON

I have a method:

public void sendMessage(MyJobDTO myJobDTO) {
    jmsTemplate.send(new MessageCreator() {

        public Message createMessage(Session session) throws JMSException {

            TextMessage message = null;
                message = session.createTextMessage(myJobDTO.toString());
                logger.info("Sending message...");
                logger.info(message);
            

            return message;
        }
    });
    
}

and my DTO’s toString():

@Override
public String toString() {
    return "{" +
            ""A":" + """ + prop_a + ""," +
            ""B":" + """ + prop_b + ""," +
            ""C":" + """ + prop_c + """ +
            "}";
}

I realise when the other application received the MQ message (using Spring Boot with JMS), the escape char appeared, causing errors. I tried to do replaceAll("\\", "") but it couldnt find anything to replace. How can I get rid of the in the message sent to the MQ?

Advertisement

Answer

The clean way to handle this is to use a proper JSON library to create the JSON string. For example, using the org.json library (javadoc).

public String toString() 
    JSONObject jo = new JSONObject();
    jo.put("A", propA);
    jo.put("B", propB);
    jo.put("C", propC);
    return jo.toString();
}

This will escape the values in propA etcetera if this is necessary. The result will be well-formed JSON.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement