SQS - Sending payload with JSONObject push empty objects - java

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;
}

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();
}

Related

Extract cloudant document in java

I received response from cloudant and I want parse the response.
My response is,
{"_id":"id_name_list","_rev":"5-9e6b089e3094955395d1c976c5d87392","1":"aa","2":"bb","3":"cc","4":"dd"}
Code to convert response to JSON is,
JSONObject jo = new JSONObject(response);
String s = jo.get("1");
I am getting the error:
org.json.JSONException: JSONObject["1"] not found.

how to convert json into string without line break and the other format

I'm setting up a new server and android, and want to send base64(image) from android to server. I use JSON for data format between android and server, so I have to put my base64 into that JSON, but the server cannot decode my base64 because there are a symbol like "\n,+," and many more. I also try using Notepad for replace "\n" but still the server wont decode it..
note:
if I use Postman the server work properly
JSONArray data = new JSONArray();
for (int i = 0; i < listImage.size(); i++) {
//listImage.get(i).setBase64(map.get(listImage.get(i).getId()));
jsonObject = new JSONObject();
jsonObject.put("id",listImage.get(i).getId());
jsonObject.put("base64",map.get(listImage.get(i).getId()));
data.put(jsonObject);
}
jsonObject = new JSONObject();
jsonObject.put("image",data);
JSONObject has toString() method that return json object data into String format. You can also look at UTF encoding to encode special character, to make http request without conflicting of special character in URL.
jsonObject = new JSONObject();
jsonObject.put("image",data);
jsonObject.toString();
Easiest way to convert jason object to a String
JSONObject json = new JSONObject();
json.toString();
thank you for your answer guys...I have found my own solution, I need to replace "\n" and "\" with "" from base64 in server side

HTTP Error Code 415 - JSON arrays in JAVA

I am trying to produce and send via JAVA a JSON file and when I am trying to add a nested object with an array in order to fit an application's protocol (which is not important to the question) the java program cannot send the file because of an HTTP error, code 415 (unsupported media type), which is strange because the produced JSON works when I copy it in the destined application (Google's DialogFlow). In other words, JSON is functional but JAVA (version 1.8) does not recognize it. Does anyone have any ideas why that happens?
When the part with the JSONArray in not included in the JSON file the request is sent without problem (see code below). I have tried changing the content-type from "application/json;charset=utf8" to "application/json;charset=utf-8" or "application/json" but nothing worked (this part in not included in the code because the changes that resulted in JSON not working were in the block below).
Part not working:
static JSONObject messageToJSON()
{
JSONObject requestJson = new JSONObject();
JSONObject meta= new JSONObject();
JSONObject payload= new JSONObject();
JSONArray arrayJson = new JSONArray();
String messageData="My Message";
try
{
requestJson.put("message", messageData);
requestJson.put("messageType", "html");
payload.put("title", "Thanks");
payload.put("message", "Thank you");
arrayJson.put(payload);
meta.put("contentType", "300");
meta.put("templateId", "6");
meta.put("contentType", "300");
meta.put("payload", arrayJson);
requestJson.put("metadata", meta);
System.out.println(requestJson.toString());
}
catch (JSONException e)
{
e.printStackTrace();
}
return requestJson;
}
The part working (without the extra layer in JSON, e.g. the payload JSON object and the arrayJson JSON array):
static JSONObject messageToJSON()
{
JSONObject requestJson = new JSONObject();
JSONObject meta= new JSONObject();
JSONObject payload= new JSONObject();
JSONArray arrayJson = new JSONArray();
String messageData="My Message";
try
{
requestJson.put("message", messageData);
requestJson.put("messageType", "html");
meta.put("contentType", "300");
meta.put("templateId", "6");
meta.put("contentType", "300");
requestJson.put("metadata", meta);
System.out.println(requestJson.toString());
}
catch (JSONException e)
{
e.printStackTrace();
}
return requestJson;
}
Ok, I found the problem. I should have transformed the arrayJson from JSONArray type to string.
In other words, instead of
meta.put("payload", arrayJson);
I should have
meta.put("payload", arrayJson.toString());
or make the arrayJson in a string format from the beginning.

gson.fromJson() method converting invalid json to valid json

In my program i am taking input from rest client in json format and retrieving the json from request body i am using gson.fromJson method for retrieving json.
BufferedReader reader = request.getReader();
JsonElement jsonElement = gson.fromJson( reader , JsonElement.class );
Input json, i am passing to rest client :
It is not a valid json.
{
"buildName":FHGF"",
"deadline":"2017-07-28T23:11:15+00:00",
"release":"0.2",
"platformRelease":"5.10.0",
"platformBuild":"1.0.0",
"releatedProducts":"##Product*****",
"expiresInPronto":"2017-07-28T23:11:15+00:00",
"changeNotesRequired":"yes",
"environment":"ah",
"stateTestedInUse":"no"
}
Json which is created by gson :
{
**"buildName":"FHGF\"\""**,
"deadline":"2017-07-28T23:11:15+00:00",
"release":"0.2",
"platformRelease":"5.10.0",
"platformBuild":"1.0.0",
"releatedProducts":"##Product*****",
"expiresInPronto":"2017-07-28T23:11:15+00:00",
"changeNotesRequired":"yes",
"environment":"ah",
"stateTestedInUse":"no"
}
Instead of throwing error gson has converted it to valid json.

Sending JSON to Rails

My issue is that the escape character is invalidating my JSON. I am sending my JSON to a Rails sever but when it arrives it gains some escape characters.
Is there something I can do to Solve this on my restfull class or is it something to be corrected on the server side?
Here is the JSON I'm sending,
[session={"password":"********","email":"********#omobile.com.br"}]
And here is the JSON thats appearing on the servers log:
{"session"=>"{\"password\":\"********\",\"email\":\"********#omobile.com.br\"}"}
I've tried these different ways to send my JSON and the result is the same:
JSONObject object = new JSONObject();
object.accumulate("email", username);
object.accumulate("password", password);
String jsonString = object.toString();
Session session = new Session();
session.setEmail(username);
session.setPassword(password);
Gson gson = new Gson();
String jsonString = gson.toJson(session, Session.class);
What happens is a mess, because neither of the strings you posted is actually JSON. The first one actually I don't know what it is, while the second one likely means that on the Ruby side you have this Ruby hash, in which the key "session" refers to a JSON-encoded hash.
We can't tell what's going on the wire because you didn't post the code, so we can't tell if your server expects a form-encoded request body, a multipart one, or directly a JSON-encoded object.
I want you to consider that the only JSON I see is the portion:
{"password": "********","email":"********#omobile.com.br"}
As I said, this can be passed as-is, or as a part in a mulipart envelope, or even url-encoded. The format is really estabilished on the server. For example I made a quick test using Apache HttpClient:
public class GsonSendToSinatra {
private static class Session {
#SuppressWarnings("unused")
String username, password;
}
public static void main(String[] args) throws Exception {
Session session = new Session();
session.username = "foo#example.com";
session.password = "qwerty1234";
Gson gson = new Gson();
String responseText = Request.Post("http://localhost:4567/echo")
.bodyString(gson.toJson(session), ContentType.APPLICATION_JSON)
.execute()
.returnContent()
.asString();
System.out.println(responseText);
}
}
and Sinatra on the server:
require 'sinatra'
require 'json'
post '/echo' do
content_type "text/plain"
layout false
session = JSON.parse request.body.read
session.map {|k,v| "#{k}: #{v}\n"}
end
I hope this example helps you to figure out what are the moving parts in a HTTP dialogue and how you can combine them.

Categories