gson JSON字符串无效

x8goxv8g  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(243)

我正在使用GSON库将java对象转换为JSON字符串。我在bean中添加数据,然后将bean添加到Array List中。现在我正在使用GSON库将列表转换为JSON字符串。JSON字符串正确,但数据不正确。我试着调试代码,发现在第一次迭代中,bean被添加到列表中,然后在第二次迭代中,bean覆盖了列表中位置0的数据,然后它在位置1添加自身。我期望的列表:

[Bean [fName=Samanyu, lName=Pandit, email=samanyumehra2000@gmail.com, username=sam123, password=null, mobile=7859857230, userImage=IMG/patient.jpg, address=412/A Ganesh Nagar 2 gali no.1 Laxmi Nagar Near Ajay cycles, Mona Pg, specialiasation=Allergist, Dentist, degree=MBBS, BDS, BAMS, experience=3, fees=3], Bean [fName=Samanyu, lName=Mehra, email=samanyumehra20000@gmail.com, username=sam, password=null, mobile=7859857230, userImage=IMG/regis.jpg, address=412/A Ganesh Nagar 2 gali no.1 Laxmi Nagar Near Ajay cycles, Mona Pg, specialiasation=Allergist, Dentist, Anesthesiologist, Cardiologist, Dermatologist, degree=MBBS, BDS, BAMS, BUMS, BHMS, BYNS, experience=3, fees=3]]

我得到的列表:

[Bean [fName=Samanyu, lName=Mehra, email=samanyumehra20000@gmail.com, username=sam, password=null, mobile=7859857230, userImage=IMG/regis.jpg, address=412/A Ganesh Nagar 2 gali no.1 Laxmi Nagar Near Ajay cycles, Mona Pg, specialiasation=Allergist, Dentist, Anesthesiologist, Cardiologist, Dermatologist, degree=MBBS, BDS, BAMS, BUMS, BHMS, BYNS, experience=3, fees=3], Bean [fName=Samanyu, lName=Mehra, email=samanyumehra20000@gmail.com, username=sam, password=null, mobile=7859857230, userImage=IMG/regis.jpg, address=412/A Ganesh Nagar 2 gali no.1 Laxmi Nagar Near Ajay cycles, Mona Pg, specialiasation=Allergist, Dentist, Anesthesiologist, Cardiologist, Dermatologist, degree=MBBS, BDS, BAMS, BUMS, BHMS, BYNS, experience=3, fees=3]]

我的Servlet代码:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection con = null;
        PreparedStatement ps = null,ps2 = null;
        ResultSet rs=null,rs2 = null;
        PrintWriter out=response.getWriter();
        HttpSession session=request.getSession(false);
        GetUserDetails details=new GetUserDetails();

        String name=request.getParameter("val");
        String sql ="select fName,lName,exp,fees,user_img,username,mob,addr,email from users where fName= ?";
        String sql2="select login_type from users where fName=?";
        String login_type="";

        List<Bean> docSearchList=new ArrayList<Bean>();
        Bean docSearchBean=new Bean();

        if(name==null||name.trim().equals(""))
            out.print("<p>Please enter name!</p>");
        else {
            try {
                con=DBConnection.createConnection();
                ps=con.prepareStatement(sql);
                ps.setString(1, name.trim());
                ps2=con.prepareStatement(sql2);
                ps2.setString(1, name.trim());
                rs=ps.executeQuery();
                rs2=ps2.executeQuery();
                if(!(rs.isBeforeFirst()))
                    out.print("<p>Record not found.</p>");
                else {
                    while(rs2.next())
                        login_type=rs2.getString("login_type");

                    if(!(login_type.equals("D")))
                        out.print("<p>Record not found.</p>");
                    else {
                        while(rs.next()) {
                            String special="";
                            String degree="";
                            List<String> list=details.getSpecialByUsername(rs.getString("username"));
                            special+=list.get(0);
                            for(String s:list) {
                                if(s.equals(special)) {}
                                else 
                                    special+=", "+s;
                            }
                            list=details.getDegByUsername(rs.getString("username"));
                            degree+=list.get(0);
                            for(String s:list) {
                                if(s.equals(degree)) {}
                                else 
                                    degree+=", "+s;
                            }
                            docSearchBean.setfName(rs.getString("fName"));
                            docSearchBean.setlName(rs.getString("lName"));
                            docSearchBean.setExperience(rs.getString("exp"));
                            docSearchBean.setFees(rs.getString("fees"));
                            docSearchBean.setUserImage(session.getAttribute("patientSearchImage")+rs.getString("user_img"));
                            docSearchBean.setMobile(rs.getString("mob"));
                            docSearchBean.setAddress(rs.getString("addr"));
                            docSearchBean.setEmail(rs.getString("email"));
                            docSearchBean.setDeg(degree);
                            docSearchBean.setSpecial(special);
                            docSearchBean.setUsername(rs.getString("username"));

                            docSearchList.add(docSearchBean);                                   
                        }
                        rs.close();                                                               
                        ps.close();                                                             
                        ps = null;                                                              

                        con.close();                                                             
                        con = null;
                    }
                    Gson gson=new Gson();
                    JsonObject obj=new JsonObject();

                    JsonElement element=gson.toJsonTree(docSearchList,new TypeToken<List<Bean>>() {}.getType());
                    System.out.println(docSearchList);
                    System.out.println("Element: "+element.toString());
                    if(docSearchBean.getfName()==null)
                        obj.addProperty("success", false);
                    else
                        obj.addProperty("success",true);

                    obj.add("docSearch",element);
                    System.out.println("Obj: "+obj.toString());
                    out.println(obj.toString());
                    out.close();

                }
            }catch (Exception e) {
                e.printStackTrace();
            }finally {                                                       
                if (ps != null) {                                            
                    try {                                                         
                        ps.close();     
                    } catch (SQLException sqlex) {                                
                        // ignore -- as we can't do anything about it here           
                    }                                                             
                    ps = null;                                            
                }                                                        
                if (con != null) {                                      
                    try {                                                   
                        con.close();                                          
                    } catch (SQLException sqlex) {                          
                        // ignore -- as we can't do anything about it here     
                    }                                                       
                    con = null;                                            
                }                                                        
            }
        }
    } 
}

请帮帮我。

osh3o9ms

osh3o9ms1#

你好,这个问题通过在while循环中初始化bean得到了解决。这是因为bean对象使用了与java指向对象的相同示例相同的值。

相关问题