gpt4 book ai didi

java简单json从数据库获取数据并显示

转载 作者:行者123 更新时间:2023-12-01 20:24:28 25 4
gpt4 key购买 nike

我想问如何生成所需的 json 输出,如下所示:

{
"Result":"OK",
"Records":[
{"PersonId":1,"Name":"Benjamin Button","Age":17,"RecordDate":"\/Date(1320259705710)\/"},
{"PersonId":2,"Name":"Douglas Adams","Age":42,"RecordDate":"\/Date(1320259705710)\/"},
{"PersonId":3,"Name":"Isaac Asimov","Age":26,"RecordDate":"\/Date(1320259705710)\/"},
{"PersonId":4,"Name":"Thomas More","Age":65,"RecordDate":"\/Date(1320259705710)\/"}
]
}

我的jsp代码如下所示:

<%@page language="java" import="java.sql.*"%>
<%@page import="java.util.*" %>
<%@page contentType="text/html; charset=UTF-8"%>
<%@page import="org.json.simple.JSONArray"%>
<%@page import="org.json.simple.JSONObject"%>
<%@page import="org.json.simple.parser.JSONParser"%>
<%@page import="org.json.simple.parser.ParseException"%>
<%
String dept = (String)request.getParameter("dept");
String sql = "SELECT * FROM employees WHERE department='"+dept+"'";

try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn=null;
conn=DriverManager.getConnection("jdbc:mysql://localhost/jspjsons","root","123456");
ResultSet rs=null;
Statement stm1=conn.createStatement();

JSONArray list = new JSONArray();
rs=stm1.executeQuery(sql);
while(rs.next())
{
JSONObject obj=new JSONObject();
obj.put("PersonId", rs.getString("id"));
obj.put("Name", rs.getString("name"));
obj.put("Age", rs.getString("age"));
obj.put("RecordDate", rs.getString("date"));

list.add(obj);
}

out.print(list);
}
catch(Exception ex)
{
out.println("<h1>"+ex+"</g1>");
}
%>

在显示输出时,总是有像这样的前括号和后括号[],我该如何去掉它?需要以 {} 开头和结尾,而不是 []

最佳答案

您正在正确创建 Records 数组(已将其存储在 list 变量中),您所需要做的就是将其添加到新的 JSONObject 以及 Result

请记住,{ ... } 表示 JSONObject[ ... ] 表示 JSONArray.

while(rs.next())
{
JSONObject obj=new JSONObject();
obj.put("PersonId", rs.getString("id"));
obj.put("Name", rs.getString("name"));
obj.put("Age", rs.getString("age"));
obj.put("RecordDate", rs.getString("date"));

list.add(obj);
}

//Include this code beneath to create the JSON you require (mainObject).
JSONObject mainObject = new JSONObject();
mainObject.put("Result", "OK");
mainObject.put("Records", list);

关于java简单json从数据库获取数据并显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44125181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com