java simple json从数据库中获取数据并显示

时间:2017-05-23 03:14:13

标签: java json

我想询问如何产生如下所示的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>");
    }
%>

同时显示输出总是有这样的前后支架[],我该如何摆脱它?需要它以{}而不是[]

开始和结束

1 个答案:

答案 0 :(得分:3)

您正在正确创建Records数组(已存储在list变量中),您需要做的就是将其与JSONObject一起添加到Result {1}}。

请注意,{ ... }表示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);
相关问题