简体   繁体   中英

How to put JSONArray of object in JSONObject inside servlet

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.

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

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM