How to put JSONArray of object in JSONObject inside servlet - java

I am trying to populate multiple selectbox dynamically using $.ajax() method....
Here is my html code......
<select id="imageSize" name="ImageSizeId"></select>
<select id="circulation" name="circulationId"></select>
Here is my servlet code.....
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/json;charset=utf-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
JSONObject usesfactors = new JSONObject();
JSONArray jArraysize = new JSONArray();
JSONArray jArraycirculation = new JSONArray();
Statement stmtsize,stmtcirculation;
ResultSet rssize,rscirculation;
int category_id = Integer.parseInt(request.getParameter("CategoryId"));
int format_id = Integer.parseInt(request.getParameter("FormatId"));
String size,display,des;
int sizeid;
try {
if(category_id == 2 && format_id == 201){
// Get image size factors
String sql1="SELECT SizeId,Size FROM Size WHERE Category_id = "+category_id+" AND Format_id = "+format_id+" ";
PreparedStatement ps1 = conn.prepareStatement(sql1);
rssize = ps1.executeQuery() ;
if( rssize!=null){
System.out.println("Not Null");// its printing even if resultset rssize has no records.......why?
while(rssize.next())
{
System.out.println("inside resultset");
JSONObject jobj = new JSONObject();
sizeid = rssize.getInt("SizeId");
size=rssize.getString("Size");
System.out.println(size);
jobj.put("SizeId", sizeid);
jobj.put("Size", size);
jArraysize.add(jobj);
}
usesfactors.put("Size", jArraysize);
rssize.close();
}
else{
System.out.println("Does not have Size factors");
}
// Get image circulation factors
String sql2="SELECT circulationId,circulation FROM Circulation WHERE Category_id = "+category_id+" AND Format_id = "+format_id+" ";
PreparedStatement ps2 = conn.prepareStatement(sql2);
rscirculation = ps2.executeQuery() ;
if(rscirculation!=null){
while(rscirculation.next())
{
JSONObject jobj = new JSONObject();
display = rscirculation.getString("DisplayName");
des=rscirculation.getString("Description");
jobj.put("DisplayName", display);
jobj.put("Description", des);
jArraycirculation.add(jobj);
}
usesfactors.put("Circulation", jArraycirculation);
rscirculation.close();
}
else{
System.out.println("Does not have Circulation factors");
}
out.println(usesfactors);
}
i am getting empty json result....?Whts wrong?
{"Size":[],"Circulation":[]}
i don't want to execute this stmt "usesfactors.put("Size", jArraysize);" if resultset rssize is null but this stmt is executing even if result set rssize has no records....
In short i want to put json array(jArraysize) in json object (usesfactors) if and only if result set rssize has records.

In response to the question in the code about why it's getting into the rssize!=null block, see the javadoc on executeQuery. It explicitly states that it never returns null, so the null check always passes. This means that an empty result set will skip the loop in that section, but still hit the line
usesfactors.put("Size", jArraysize);
This should be rewritten to actually avoid the insert on an empty return set. A similar change should be made to correct the circulation section, which also does an ineffective null check.
while(rssize.next())
{
System.out.println("inside resultset");
JSONObject jobj = new JSONObject();
sizeid = rssize.getInt("SizeId");
size=rssize.getString("Size");
System.out.println(size);
jobj.put("SizeId", sizeid);
jobj.put("Size", size);
jArraysize.add(jobj);
}
if (jArraysize.length > 0)
{
usesfactors.put("Size", jArraysize);
}
else
{
System.out.println("Does not have Size factors");
}
rssize.close();

The problem in your code might be your sql queries which are not returning any values.because i have done in my IDE in the same way you have done,only difference is that instead of getting values from database i have kept manually by iterating for loop.below is the code...
JSONObject usesfactors = new JSONObject();
JSONArray jArraysize = new JSONArray();
JSONArray jArraycirculation = new JSONArray();
for(int i=0;i<3;i++)
{
JSONObject jobj = new JSONObject();
jobj.put("SizeId", "1");
jobj.put("Size", "2");
jArraysize.put(jobj);
}
usesfactors.put("Size", jArraysize);
for(int i=0;i<3;i++)
{
JSONObject jobj = new JSONObject();
jobj.put("DisplayName", "3");
jobj.put("Description", "4");
jArraycirculation.put(jobj);
}
usesfactors.put("Circulation", jArraycirculation);
System.out.println(usesfactors);

Related

JDBC returns null value in resultSet using where condition. I tried to get all columns but its not returning any value

I want to get all the data from the database using a where condition. But resultSet returning null values. But when I use an Integer instead of string it works fine, but that I don't want.
I'm not many experts in SQL but when I run a query in SQL server it works fine.
public JSONObject searchInternship1(String Category) throws SQLException {
ResultSet result;
Connection con = null;
PreparedStatement stmt = null;
JSONArray jsonArray = new JSONArray();
JSONObject mainObject1 = new JSONObject();
JSONObject jsonObject = new JSONObject();
try {
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
con = DriverManager.getConnection("jdbc:oracle:thin:#144.217.163.57:1521:XE", "mad310team2", "anypw");
String sql;
sql = ("SELECT * FROM INTERNSHIP WHERE CATEGORY= ?");
stmt = con.prepareStatement(sql);
// con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
stmt.setString(1, Category);
result = stmt.executeQuery();
System.out.println("resultttt " + result);
String status;
Instant instant = Instant.now();
long time = instant.getEpochSecond();
if (result.next() == false) {
status = "Failed";
mainObject1.accumulate("Status :", status);
mainObject1.accumulate("Timestamp :", time);
mainObject1.accumulate("Message :", " Fetching Failed");
mainObject1.accumulate("why not", Category);
// System.out.println("hellooooo "+ result);
} else {
do {
mainObject1.accumulate("why not111", Category);
status = "Success";
jsonObject.accumulate("Id :", result.getInt("INT_ID"));
jsonObject.accumulate("CONTACT PERSON", result.getString("CONTACT_PERSON"));
jsonObject.accumulate("INCENTIVE", result.getString("INCENTIVE"));
jsonObject.accumulate(" VENUE", result.getString("VENUE"));
jsonObject.accumulate("DATE OF TEST", result.getDate("DATE_OF_TEST").toString());
jsonObject.accumulate("DATE OF TEST", result.getString("TIME_OF_TEST"));
jsonObject.accumulate("PROCEDURE", result.getString("PROCEDUREE"));
jsonObject.accumulate("No. OF VACANCIES", result.getInt("NO_OF_VACANCIES"));
jsonObject.accumulate("COMPANY ID", result.getInt("COMPANY_ID"));
jsonObject.accumulate("CATEGORY", result.getString("CATEGORY"));
jsonArray.add(jsonObject);
jsonObject.clear();
} while (result.next());
// result = result + r.getString("data");
mainObject1.accumulate("Details of jobs: ", jsonArray);
}
stmt.close();
con.close();
} catch (SQLException ex) {
// System.out.println("Error at111:" + ex.getClass().getName() + ex.getMessage());
Logger.getLogger(Register_Detail.class.getName()).log(Level.SEVERE, null, ex);
}
return mainObject1;
}
#GET
#Path("searchInternship&{value1}")
#Produces(MediaType.TEXT_PLAIN)
public String searchInternship(#PathParam("value1") String Category)
throws SQLException {
JSONObject result = searchInternship1(Category);
return result.toString();
}
I don't believe this is a JDBC issue. I believe this is an issue with how you are reading the data out of the result set.
At the top of your createInternship1 method you create a JSONObject object. Let's suppose at least one row comes back from the result set. For the first row read from the result set, your code then reads the values out of the result set and writes them into your JSONObject, before adding your JSONObject to your JSON array jsonArray.
So far, your code is doing what you want it to. You have a JSON array with a single object in it, containing the data read from the first row in the result set. However, the problem comes with your next step.
You then clear your JSONObject.
Your array doesn't contain a copy of your JSONObject, it contains the same object.
So at this point, your array now contains a single empty JSONObject. The data you read out of the result set has been deleted.
As your code proceeds through further rows in the result set, it encounters another problem. It reads more data into the same JSONObject created earlier, adds this same JSONObject (which is already in the array) to the array and then clears this same JSONObject again. You therefore end up with a JSON array containing the same empty JSONObject once for each row read from the result set.
I figured you're using the json-simple library for handling JSON. Initially I thought you were using org.json, but the JSONObject class in that library doesn't have a clear() method, whereas json-simple's JSONObject class does have this method. json-simple's JSONObject class extends java.util.HashMap, and calling the get() method of a HashMap returns null for a key that is not in the map. Your one JSONObject is empty, so no keys are in the map, and so null will always be returned from any call to the get() method of this object. This hopefully explains why you are getting null values returned.
You can fix this by creating a new JSONObject for each iteration of your do ... while loop instead of once at the top, adding that to your JSON array, and removing the line that clears the JSON object:
do {
JSONObject jsonObject = new JSONObject(); // add this line
mainObject1.accumulate("why not111", Category);
status = "Success";
jsonObject.accumulate("Id :", result.getInt("INT_ID"));
jsonObject.accumulate("CONTACT PERSON", result.getString("CONTACT_PERSON"));
// ... various similar lines omitted for clarity
jsonObject.accumulate("CATEGORY", result.getString("CATEGORY"));
jsonArray.add(jsonObject);
} while (result.next());
You'll also need to delete the line JSONObject jsonObject = new JSONObject(); further up in your code.

Can't get all dataColumn values by ResultSet

I have table named testTable( in sql server 2014) and i have one column called holidays inside it , in my case i have two values inside this column for example (2018-03-02 and 2018-04-02) and i use this method for getting this value and then puttinh it in json Object here is my code:
public static JSONArray convertToJSON(ResultSet resultSet) throws Exception {
JSONArray jsonArray = new JSONArray();
JSONObject obj = new JSONObject();
while (resultSet.next()) {
int total_rows = resultSet.getMetaData().getColumnCount();
for (int i = 0; i < total_rows; i++) {
jsonArray.put(obj.put(resultSet.getMetaData().getColumnLabel(i+1)
.toLowerCase(), resultSet.getObject(i+1)));
}
}
System.out.println(jsonArray);
return jsonArray;
}
but when i run this code i got only last data written two times in my array it will look like this :
[{"startDate":2018-03-02},{"startDate":2018-03-02}]
but it should look like this:
[{"startDate":2018-03-02},{"startDate":2018-03-03}]
I mean it writes last data twice but when i try to print it in console i got right values?
what should i change to get all startDate values properly?
You are overwriting the record by doing the following operation
jsonArray.put(obj.put(resultSet.getMetaData().getColumnLabel(i+1)
.toLowerCase(), resultSet.getObject(i+1)));
While putting the object your key is startdate which gets overwritten
obj.put(resultSet.getMetaData().getColumnLabel(i+1)
.toLowerCase(), resultSet.getObject(i+1))
Also, there is something wrong with your logic. The following code will give you column count and NOT the row count
int total_rows = resultSet.getMetaData().getColumnCount();
You can use the following snippet to get the object:
public static JSONArray convertToJSON(ResultSet resultSet) throws Exception {
JSONArray jsonArray = new JSONArray();
while (resultSet.next()) {
JSONObject obj = new JSONObject();
obj.put("startDate" , resultSet.getString('holidays'))
jsonArray.put(obj);
}
return jsonArray;
}

Array inside an array using JSON

This is code in JAVA I used JSONArray and method JSONarray.put(string);
public JSONArray getChart() {
Connection con = getConnectionObject();
Statement st = null;
ResultSet rs = null;
JSONObject jCharto = new JSONObject();
JSONArray arr = new JSONArray();
try {
st = con.createStatement();
String query = "select count(books_issued) as books_issued,command from fact_aaglib, school where fact_aaglib.school_name = school.school_name group by command;";
rs = st.executeQuery(query);
System.out.println("['Command','Book Issued'],");
while (rs.next())
{
String zone = rs.getString("command");
arr.put(zone);
int booksissued = rs.getInt("books_issued");
arr.put(booksissued);
}
System.out.println(arr+",");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (con != null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return arr;
}
Here is my output
['Command','Book Issued'],["Central",324,"Southern",312,"South-West",192,"Eastern",264,"Northern",84,"Western",396],
But actual I want output like this:
[
['Command', 'Books Issued'],
["Central",324],["Southern",312],
["South-West",192],
["Eastern",264],
["Northern",84],
["Western",396]
]
And this data is using in google charts to draw bar chart .
A JSONArray is not limited to strings.
You need to create one array for holding records, then create a new one for each pair or records. Here is the basic idea:
// create the "top" array
JSONArray topArray = new JSONArray();
// add your static "headers"
JSONArray headers = new JSONArray();
headers.put("Command");
headers.put("Book Issued");
topArray.put(headers);
while (rs.next()){
// create a new array for the current record
JSONArray recordArray = new JSONArray();
// populate the record array
String zone = rs.getString("command");
recordArray.put(zone);
int booksissued = rs.getInt("books_issued");
recordArray.put(booksissued);
// append the record array to the top array
topArray.put(recordArray);
}
return topArray;

Method inside the method

I written the below code
List<UserDetails> getUserList(String Json){
try {
JSONObject jsonObject = new JSONObject(Json);
int myname = jsonObject.getInt("itemsPerPage");
System.out.println(myname);
JSONArray jsonarray = (JSONArray) jsonObject.get("list");
System.out.println(jsonarray.length());
if(null != jsonarray && jsonarray.length() == 25){
RestClient restClient = new RestClient();
URL= someurl;
checkValue="USERDETAILS";
startIndex += 25;
String jsonResult = restClient.postJiveUsersData(URL,restUserName,restPassword);
if(null != jsonResult) {
getUserList(jsonResult);
}
}
System.out.println("User List size::" +userDetailsList.size());
return userDetailsList;
After executing the above the "User List size" is printing more than once. May I know reason and is there any way to avoid tomultiple time to print it.
Thanking for helping in advance.
Regards
Narasimha Reddy P
It is printing more than once because your getUserList method is calling itself, so System.out.println("User List size::" +userDetailsList.size()); is executed multiple times.

Json Array not properly generated

I have written java code for generating json of my searched data from file.But its not generating exact JsonArray. Its like
[{"item":"1617"},{"item":"1617"}]
instead of
[{"item":"747"},{"item":"1617"}].
Here 1617 is last item which is fetched from file.
JSONArray ja = new JSONArray();
JSONObject jo = new JSONObject();
while (products.readRecord())
{
String productID = products.get("user");
int j = Integer.parseInt(productID);
if(j == userId) {
itemid = products.get("item");
jo.put("item",itemid);
ja.add(jo);
}
}
out.println(ja);
products.close();
you are actually creating one jSONobject object to handle two objects, shouldn't you need to create JSONObjects in the while loop? something like this, so every iteration in while loop will create a new JSONObject and add it to JSONArray
JSONArray ja = new JSONArray();
while (products.readRecord())
{
String productID = products.get("user");
int j = Integer.parseInt(productID, 10);
if(j == userId)
{
JSONObject jo = new JSONObject();
itemid = products.get("item");
jo.put("item", itemid);
ja.add(jo);
}
}
out.println(ja);
products.close();
Extra:
i am not sure how java does conversion for string to integer, but i think you should always specify radix when using parseInt so the strings like '09' will not be treated as octal value and converted to wrong value (atleast this is true in javascript :))
Integer.parseInt(productID, 10);
You must re-instantiate your JSonObject inside the loop because when you modify it you modify the underlying object which is referenced several times by your array. Move your JSONObject jo = new JSONObject(); inside the loop and it should work fine.
Place JSONObject jo = new JSONObject(); inside the loop:
while (products.readRecord())
{
JSONObject jo = new JSONObject();
String productID = products.get("user");
int j = Integer.parseInt(productID);
// etc
}

Categories