how to send response in json to a tree structure in servlet - java

i am new to servlet and i succeeded to send a json format to the client using json-simple package/jar file; and import it like-
import org.json.simple.JSONObject;
and to get response in json i have following code-
response.setContentType("application/json");
JSONObject obj = new JSONObject();
obj.put("name", "veshraj joshi");
obj.put("id",request.getParameter("id"));
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
out.println(obj);
and its format is like:
{"name":"veshraj joshi","id":"","num":"100","balance":"1000.21"}
and works fine,
but i need json format like-
{ status:"ok",
message:"record has been added successfully",
data:{
name:"veshraj joshi",
email:"email#gmail.com",
address:"kathmandu, Nepal"
}
}
and dont have any idea how to achieve this in servlet;

It works fine while try to make nested json and new code become-
response.setContentType("application/json");
JSONObject obj = new JSONObject();
JSONObject obj1 = new JSONObject();
obj1.put("email",'email#gmail.com');
obj1.put("name", "veshraj joshi");
obj1.put("id",request.getParameter("id"));
obj1.put("num", new Integer(100));
obj1.put("balance", new Double(1000.21));
obj.put("status","ok");
obj.put("message","record has been added successfully");
obj.put("data",obj1);
out.println(obj);

Related

Problems with JSONObject vs JSONArray in Android

I have a pretty specific problem I guess. I'm using Volley library to get a String response from URL, the response is following:
{"email":"imribar#gmail.com","phone":"7(707)111-11-11","family_name":"Жилин","name":"Иван","role":0}
I get this response by converting my SQL query array to JSON in PHP
$output=$db->query("SELECT email, phone, family_name, name, role FROM users WHERE email=?", "$email")->fetchArray();
$json=json_encode($output, JSON_UNESCAPED_UNICODE);
echo"$json";
What I need to do next is go throught this JSON and insert records to local database in my Android APP. In order to do that, I do following:
if(response.contains("email")) {
testResponse.setText("Response is2: " + response);
try {
JSONArray jsonArr = new JSONArray(response);
for(int i=0; i < jsonArr.length();i++){
JSONObject jsonObj = jsonArr.getJSONObject(i);
Log.i("User",jsonObj.toString());
User user = new User();
user.email= jsonObj.getString("email");
user.phone=jsonObj.getString("phone");
user.firstName=jsonObj.getString("name");
user.lastName=jsonObj.getString("family_name");
user.role=jsonObj.getInt("role");
user.token="123123123fsadf";
insertUser inewuser = new insertUser();
inewuser.execute(user);
}
} catch (JSONException e) {
Log.i("JSONerror", e.toString());
}
}
I keep getting the following error:
13:24:59.518 22389-22389/com.local.school I/JSONerror: org.json.JSONException: Value {"email":"imribar#gmail.com","phone":"7(707)111-11-11","family_name":"Жилин","name":"Иван","role":0} of type org.json.JSONObject cannot be converted to JSONArray
Any idea what I can do on PHP side to change the JSONString (add [], or add a name to an array), or what do I need to do in Android?
Your response does not have a json array, only an object. 
Array is something like this. 
[{
"email": "imribar1#gmail.com",
"phone": "7(707)990-77-72",
"family_name": "Жилин2",
"name": "Иван2",
"role": 2
},
{
"email": "imribar#gmail.com",
"phone": "7(707)990-77-71",
"family_name": "Жилин",
"name": "Иван",
"role": 0
}
]
So remove the  loop and try. 
if(response.contains("email")) {
testResponse.setText("Response is2: " + response);
try {
JSONObject jsonObj = jsonArr.getJSONObject(i);
Log.i("User",jsonObj.toString());
User user = new User();
user.email= jsonObj.getString("email");
user.phone=jsonObj.getString("phone");
user.firstName=jsonObj.getString("name");
user.lastName=jsonObj.getString("family_name");
user.role=jsonObj.getInt("role");
user.token="123123123fsadf";
insertUser inewuser = new insertUser();
inewuser.execute(user);
} catch (JSONException e) {
Log.i("JSONerror", e.toString());
}
}
I suggest you use a JsonObjectRequest instead of StringRequest when you call Volley in your app. It is almost the same as StringRequest but it gets a JSONObject as an answer.
String url = "http://my-json-feed";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// your cose goes here:
JSONObject jsonObject = new JSONObject(response.toString());
User user = new User();
user.email= jsonObject.getString("email");
user.phone=jsonObject.getString("phone");
user.firstName=jsonObject.getString("name");
user.lastName=jsonObject.getString("family_name");
user.role=jsonObject.getInt("role");
user.token="123123123fsadf";
insertUser inewuser = new insertUser();
inewuser.execute(user);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
jsonObjectRequest
Your json string has a json object as root object, while in code you are using JSONArray jsonArr = new JSONArray(response); to parse it as if it were an array. Assuming your used json library, you would have to start parsing the json using:
JSONObject jsonObj = new JSONObject(response);
The alternative would be to actually generate a json array ([...]) rather than a json object ({...}) so that your parsing code will recognise it. The choice you want to make will depend on whether you always send a single json object or whether you want to be able to send multiple json objects (in a json array).

Java JSONArray Object Returns HTML Format?

I am using Java Spring and I am trying to return a JSON object in json format. However my controller below returns a funny HTML format for JSON data, see below.
I want the controller to return the data as JSON formatted data not XML...
Any Ideas?
Thanks,
Pete
Data Returned:
<JSONArray><item><date><date>11</date><hours>15</hours><seconds>52</seconds>
<month>11</month><nanos>0</nanos><timezoneOffset>300</timezoneOffset>
<year>117</year><minutes>32</minutes><time>1513024372000</time><day>1</day>
</date><exception></exception><level>DEBUG</level>
<logger>com.foo.bar.webapp.controller.ReconcileController</logger><id>91</id>
<message>filter was empty</message></item><item><date><date>11</date>
<hours>15</hours><seconds>52</seconds><month>11</month><nanos>0</nanos>
<timezoneOffset>300</timezoneOffset><year>117</year><minutes>32</minutes>
<time>1513024372000</time><day>1</day></date><exception></exception>
<level>DEBUG</level><logger>com.foo.bar.webapp.controller.ReconcileController
</logger><id>92</id><message>returning labels as string</message>
</item><item><date><date>11</date><hours>15</hours><seconds>52</seconds>
<month>11</month><nanos>0</nanos><timezoneOffset>300</timezoneOffset>
<year>117</year><minutes>32</minutes><time>1513024372000</time><day>1</day>
</date><exception></exception><level>DEBUG</level>
<logger>com.foo.bar.webapp.controller.ReconcileController...
Controller Method :
#RequestMapping("/data*")
#Produces("application/json")
#ResponseBody
public JSONArray getData() {
List<LogEntry> logs = logEntryManager.getLogsByDate( new Date() );
JsonConfig config = new JsonConfig();
config.addIgnoreFieldAnnotation(com.fasterxml.jackson.annotation.JsonIgnore.class);
Log.trace("Get LogEntry Data Only");
JSONArray jsonArray = JSONArray.fromObject( logs, config );
return jsonArray;
}
#RequestMapping(value = "data", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON) // import javax.ws.rs.core.MediaType
public #ResponseBody JSONArray getData() {
List<LogEntry> logs = logEntryManager.getLogsByDate( new Date() );
JsonConfig config = new JsonConfig();
config.addIgnoreFieldAnnotation(com.fasterxml.jackson.annotation.JsonIgnore.class);
Log.trace("Get LogEntry Data Only");
JSONArray jsonArray = JSONArray.fromObject( logs, config );
return jsonArray;
}
ignore your #Produces annotation
try this.

Get response JSON object webservice RESTful java

When I access my URL http://localhost:8081/projectName/pathh/param to show me the JSON Object created
"Employee": [{
"id": "param"
}]
This is my code in Java. I use Eclipse + Tom Cat Server.
#Path("/pathh")
#GET
#Path("{parameter}")
public Response getJSONObj(#PathParam("parameter") String parameter) {
JSONObject jsonObj = new JSONObject();
JSONArray jsonarray = new JSONArray();
jsonObj.put("id", parameter);
jsonarray.put(jsonObj);
System.out.println(jsonarray);
JSONObject jsonMain = new JSONObject();
jsonMain.put("Employee", jsonarray);
System.out.println(jsonMain.toString());
System.out.println(Response.status(200).entity(jsonMain).build());
return Response.status(200).entity(jsonMain).build();
}
I get that error :
HTTP Status 500 - java.lang.IllegalArgumentException: wrong number of
arguments
type Exception report
message java.lang.IllegalArgumentException: wrong number of arguments
description The server encountered an internal error that prevented it
from fulfilling this request.
package com.tests;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
#Path("/path/{parameter}")
public class Test1 {
#GET
public Response getJSONObj(#PathParam("parameter") String parameter) {
JsonObject jsonObj = new JsonObject();
JsonArray jsonarray = new JsonArray();
jsonObj.addProperty("id", parameter);
jsonarray.add(jsonObj);
System.out.println(jsonarray);
JsonObject jsonMain = new JsonObject();
jsonMain.add("Employee", jsonarray);
System.out.println(jsonMain.toString());
System.out.println(Response.status(200).entity(jsonMain).build());
return Response.status(200).entity(jsonMain.toString()).build();
}
}
I have used Jersey as the Jax-RS API implementation. jersey-server and jersey-servlet are included as dependencies and web.xml has an entry for the jersey servlet mapping.
It would help if you could debug it and find the line it's failing on, or whether it never makes it into the method and you have a problem with your application wiring/annotations.
That said, I suspect that if you delete or comment out the line
System.out.println(Response.status(200).entity(jsonMain).build());
it will work.

Not able to convert DBCursor to JSON array {MongoDB }"Could not write content: JSONObject is not assignable to JSONArray "

I am newbie, forgive me if this sounds silly.
I am trying to convert a cursor returned by mongo collection into a json object. Such that, when I hit this particular url(localhost:8080/TestReqHere) I receive a list of model object in json format. But the code below does not work as expected.
Note that if i do table.find().toArray() and change the return type to List<DBObject> it works fine. I get a json like response.
#RestController
public class TestController {
#RequestMapping(value = { "/TestReqHere" }, method = RequestMethod.GET)
public List<JSONArray> getTestReqHere( HttpServletResponse response) throws Exception {
JSONArray jsonarray = new JSONArray();
JSONObject jsonobj = new JSONObject();
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("someList");
DBCollection table = db.getCollection("someList");
DBCursor cursor = table.find();
while(cursor.hasNext()) {
BasicDBObject obj = (BasicDBObject) cursor.next();
jsonobj = new JSONObject();
jsonobj.put("col1", obj.getString("col1"));
jsonobj.put("col2", obj.getString("col2"));
jsonobj.put("_id", obj.getString("_id"));
jsonarray.add(jsonobj);
}
return jsonarray;
}
A normal program to convert object to / from JSON using Jackson works fine for me but when run on server I get the below error: Could you please let me know where I am going wrong.
HTTP Status 500 - Could not write content: Class
org.json.simple.JSONObject is not assignable to
org.json.simple.JSONArray (through reference chain:
org.json.simple.JSONArray[0]); nested exception is
com.fasterxml.jackson.databind.JsonMappingException: Class
org.json.simple.JSONObject is not assignable to org.json.simple.JSONArray
(through reference chain: org.json.simple.JSONArray[0])

How should I output json from JSONArray using jax rs/jersey? [duplicate]

This question already has answers here:
Jersey 415 Unsupported Media Type
(3 answers)
Closed 7 years ago.
My restful API method looks like this
#GET
#Produces(MediaType.APPLICATION_JSON)
public JSONArray getMessage()
{
FreeDriversService f=new FreeDriversService();
try {
return f.executeFreeDrivers(); // this method return a JSONArray
}
catch(Exception e) {
System.out.println(e.toString());
return new JSONArray();
}
}
When I use the toString() method on JSONArray it does produce a result, but I would like JSON as output. How can i do that?
I am getting this error
A message body writer for Java class org.json.JSONArray, and Java type class org.json.JSONArray, and MIME media type application/json
was not found
Problem Summary:-
You have mentioned the output as JSON in the #Produces annotation as #Produces(MediaType.APPLICATION_JSON) but instead of sending JSONObject your method getMessage is returning JSONArray.
You can not convert a JSON to an JSONArray simply, because in JSONArray same type of JSONObject can be repeated multiple times with same keys, which can be replaced by the later values of the multiple JSONObject.
Solution :-
You can create a JSONObject and can put the JSONArray inside it as a value for a user defined key.
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getMessage(){
JSONObject finalJson = new JSONObject ();
JSONArray inputArray = new JSONArray();
FreeDriversService f=new FreeDriversService();
try{
inputArray = f.executeFreeDrivers(); // this method return a JSONArray
}catch(Exception e){
System.out.println(e.toString());
}
finalJson.put("array",inputArray );
return Response.status(200).entity(finalJson).build();
}

Categories