2

I was testing different payload structures accepted by AWS SDK (org.springframework.cloud:spring-cloud-starter-aws-messaging:2.2.6.RELEASE). I am sending the message using convertAndSend function provided by QueueMessagingTemplate. I am able to send it successfully with a string payload or a custom java object. However, when I convert my custom java object to a JSONObject, and push the JSONObject to SQS, it seems the the messageBody being pushed is {empty:true}. When I send it with jsonObject.toString(), it works well though. I am confused on why convertAndSend works for custom java class/object but not for JSONObject type.

Below is a sample code on how I am doing the JSON conversion:

public JSONObject toJson() throws Exception {
    JSONObject json = new JSONObject();
    json.put("payload", this.payload);
    json.put("id", this.taskId);
    return json;
}
Gayathry S
  • 91
  • 11
  • I would like to know why jsonobject cannot be converted automatically like a custom object.....the reasoning behind. As alternatives, I have already found out that I can send it as a string using .toString() or the java object itself. However, it is bugging me why a java type class fails to convert where a custom class can. – Gayathry S Jan 30 '23 at 13:10

1 Answers1

0

SQS only allows message content that is JSON formatted string. JSONObject is a Java object. To get it to a JSON formatted string your method needs to look like this:

public String toJson() throws Exception {
    JSONObject json = new JSONObject();
    json.put("payload", this.payload);
    json.put("id", this.taskId);
    return json.toString();
}
John Williams
  • 4,252
  • 2
  • 9
  • 18
  • I have done this for now. But what I dont get is...the conversion that happens for a custom java object - why is that not happening to a json object? Why would convertandsend fail there, and even without giving a "messageconversion error", push an empty payload? – Gayathry S Jan 30 '23 at 13:07
  • Does the custom java object belong to a class that implements Serializable? – John Williams Jan 30 '23 at 13:10
  • Here is my custom object: ```@Data public class Response { // * Payload pushed into tenant queue */ private Map payload; private Long taskId; }``` – Gayathry S Jan 30 '23 at 13:12
  • I am totally mystified. – John Williams Jan 30 '23 at 13:29