Empty object in browser when returning JSONObject - java

I have this method :
#GET
#Path("/myservice")
#Produces(MediaType.APPLICATION_JSON)
public Response mysercice() {
boolean userExists = false;
CacheControl cacheControl = new CacheControl();
cacheControl.setNoCache(true);
cacheControl.setNoStore(true);
JSONObject jsonObject = new JSONObject();
jsonObject.put("userExists", userExists);
return Response.ok(jsonObject, MediaType.APPLICATION_JSON).cacheControl(cacheControl).build();
}
When accessing to the URL of the method in the browser, I get { }, it means that the object is empty.
So, I tried to use :
return Response.ok(jsonObject.toString(), MediaType.APPLICATION_JSON).cacheControl(cacheControl).build();
So, I get in the browser {"userExists" : false}
But I didn't understand why when returning simply the JSONObject, we get in the browser an empty object.

Most JAX-RS implementations come with a provider for mapping response entities to JSON. So when you write:
return Response.ok(jsonObject, MediaType.APPLICATION_JSON).build();
You are basically requesting that the JAX-RS provider marshall the JSONObject into JSON for you. The only problem being that JSONObject isn't really meant to be serialized this way. Instead its meant to be used to build a JSON representation incrementally, then convert that representation into a JSON string value. You have two options:
Create a POJO containing all the fields you want to send back to the client. Return this POJO in your method and it will be automatically converted to JSON (`return Response.ok(myPojo, MediaType.APPLICATION_JSON).build()
Return the JSON data directly as a String (which you already did in your example that works).

Related

Unexpected JSon response from Spring Rest API Controller

I have a method in my Spring controller, in which I am returning an object containing a spring attribute with a value "\HelloWorld". To store it into Java String object I have to put escape character, then the string becomes "\\HelloWorld". When I print, that works totally fine and prints "\HelloWorld". but when I return it in JSon response, it's returning "\\HelloWorld".
But I want it to return "\HelloWorld".
Bellow is the snippet:
#RequestMapping("")
#ResponseBody
public MyDataObject greeting() {
MyDataObject f = new MyDataObject();
f.setMessage("\\HelloWorld");
return f;
}
It's Json response is "message":"\\HelloWorld", but I want it "\HelloWorld".
Note: I don't want to unescape manually specific to that string.
You can use a library such as Jakson and it will internally handle such complexities.
MyDataObject f = new MyDataObject();
f.setMessage("\\HelloWorld");
String payload = new ObjectMapper().writeValueAsString(params);

String deserialization and conversion to JSON in Java

After deserializing my string and converting it to JSON using the code below:
JSONObject returnValue = new JSONObject();
String toJson = null;
try
{
Object otherObjectValue = SerializationUtils
.deserialize(myBytesArray);
Gson gson = new Gson();
toJson = gson.toJson(otherObjectValue);
returnValue.put(key, toJson);
}
some part of the JSON still has something like:
{ "key":"ATTRIBUTE_LIST", "value":"{\"attributeContract\":[{\"scope\":\"sso\",\"name\":\"SAML_SUBJECT\",\"description\":\"Click to Edit\",\"required\":true}]}"}
which means everything in:
"{\"attributeContract\":[{\"scope\":\"sso\",\"name\":\"SAML_SUBJECT\",\"description\":\"Click to Edit\",\"required\":true}]}"
is one string instead being another object with fields. Is there something I can do to sanitize by JSONObject to make it properly JSON?
The key part is OK, means the whole String is JSON formatted.
For the value part, /shows that the value of value is JSON formatted already.
So you may "deserialize" the value of value again to retrieve an Object result. Or you may ask the creator of origin JSON, to serialize origin Object one time into JSON format.

JSON response appended with extra properties using jQuery File-Upload plugin in Struts 2

I'm using jQuery File-Upload plugin with Struts 2.
In my action I am populating the JSON object "results" and that's all I want my action to return.
But it is also including the plugin's file object as well which is an incomplete JSON and causing everything to break on my callbacks.
(Please note that if I don't populate my result object then it will return a valid JSON "file" object.
Is there any way I could avoid returning the "file" JSON response? I just want my action to return only "results"
{
"results": [
{
"ExcelPath": "/usr/test/test.xlsx",
"ExcelName": "test.xlsx",
"TestExcelStatus": "success"
}
]
}
{
"file": {
"absolute": true,
"absoluteFile": null,
"absolutePath": "\/usr\/local\/apache-tomcat-7.0.39\/temp"
},
"path": "\/usr\/local\/apache-tomcat-7.0.39\/temp\/up
My Action is as below:
org.json.JSONObject resp = new JSONObject();
JSONArray resultsArray = new JSONArray();
resp.put("results",resultsArray);
JSONObject result = new JSONObject();
result.put("TestExcelStatus", "success");
result.put("ExcelName", this.fileFileName);
result.put("ExcelPath", fileToCreate.getPath());
resultsArray.put(result);
servletResponse.reset();
servletResponse.setHeader("Content-Type","application/json; charset=UTF-8");
servletResponse.setHeader("CacheControl","no-cache");
servletResponse.setHeader("Pragma","no-cache");
servletResponse.setHeader("Expires","-1");
//resp.writeJSONString(out);
resp.write(servletResponse.getWriter());
I am expecting the below line to clear the existing JSON and only return my "results" JSON. But it is still returning every thing.
servletResponse.reset();
And the desired JSON response must be as below without a "file".
{
"results": [
{
"ExcelPath": "/usr/test/test.xlsx",
"ExcelName": "test.xlsx",
"TestExcelStatus": "success"
}
]
}
The Struts action is always returning a result code that is used by the action invocation to execute a result configured to this action. I suspect that result is of type json.
If the action returning json result then by default the root property is initialized to the action instance or a model if you are using model-driven action.
It means that all public properties of the root object will be serialized to JSON. You can control this process with annotations placed on the properties, or configure the result with parameters to include/exclude some properties from the result.
Actually you only need to configure the root parameter of the result to return an object that you serialize to JSON. But because you are writing to response directly you can change the result code returned by the action to NONE. This is used by the actions that don't return any result.

Jackson Json not reading my json correctly

I have some json sent to my playframework site as a byte[] using the POST method.
Here is an example of the json
{
"productFamily": "abcd",
"currentVersion": "12d11e3",
"serialNumber": "asdfasfdasdf",
"modelNumber": "sdfsfdasf",
"productCode": "safasdfsdfasdfsdfsd"
}
I'm trying to load it into a JsonNode using this code:
public static Result submit() {
JsonNode recievedJson = request().body().asJson();
Eclipse debug says recievedJson has
_value = "{\r\n "productFamily": "abcd",\r\n "currentVersion": "12d11e3",\r\n "serialNumber": "asdfasfdasdf",\r\n "modelNumber": "sdfsfdasf",\r\n "productCode": "safasdfsdfasdfsdfsd"}"
How come my json string isn't being parsed from the request body into the JsonNode obj?
When I try to call JsonNode methods on recievedJson I dont get the expected results. for example recievedJson.get(0) returns null and recievedJson.fields() returns null
Object item = recievedJson.get("productFamily");
Eclipse debug shows item = null.
Object item = recievedJson.fields();
returns an empty iterator
You are trying to access array node with get(int) method, whereas your json is an object. Try using get(String) methods instead, where String is your key name.

How to create a Json Object with empty strings and send it as a Web Service Response

I was querying and getting data from database using Spring jdbctemplate rowmapper. Once I get the data I was mapping it to a Java object and converting it to a json object.
My json object contains contains a object with 2 fields
code
status
When I was getting the data from database I was passing 200 and success data to the above 2 fields and passing the json object as web service response.
My actual question is even if I didn't get any data, I need to pass the json object as web service response but with code as "404" amd message field as "no data" and other fields are to be empty strings ("") , similarly if any exception occurred, need to send json object with empty strings but with 503 code.
How can I do that?
My method code snippet:
userdtls= userDaoimpl.getUserdetails(userId);
if (userdtls== null) {
ResponseBuilder builder = Response.ok(convertToJson(userdtls),MediaType.APPLICATION_JSON).status(Status.NOT_FOUND).entity("No such user " + userdtls+);
throw new WebApplicationException(builder .build());
}
convertToJson.java
public String convertToJson(UserData userdtls) {
StatusData status = new StatusData ();
status.setCode("200");
status.setMessage("Success");
userdtls.setStatus(status);
PersonalData personal = new PersonalData();
personal.setdob("june11");
personal.setage("28");
userdtls.setPersonal(personal);
Gson gson = new GsonBuilder().serializeNulls().create();
return gson.toJson(userdtls));

Categories