-1

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?

xcoder
  • 1,336
  • 2
  • 17
  • 44

1 Answers1

0

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • thanks a lot! By any chance you know how I can fix the same problem if I need to return an XML instead of JSON? – xcoder Mar 30 '21 at 02:23
  • I believe that there are APIs for doing the equivalent, but I'm not that familiar with them. There should be other existing Q&As that explain. – Stephen C Mar 30 '21 at 03:25