0

这是我的 servlet,我成功地从数据库中读取数据并将其显示在浏览器中,但我想以 json 格式显示这些数据,谁能告诉我

package com.file;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetDataTable extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("application/json");
PrintWriter pw = res.getWriter();
Connection con;
Statement stmt;
ResultSet rs;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:java","java","java");
stmt = con.createStatement();
rs = stmt.executeQuery("Select * from SERIESCHART");

pw.println("DATA "+ "VALUE" + "<br>");
while(rs.next())
{
pw.println(rs.getString(1)+" "+rs.getString(2) + "<br>");
}
}
catch (Exception e){
pw.println(e);
}
}
}
4

2 回答 2

1

您可以使用json-simple

示例代码

      import org.json.simple.JSONObject;
      JSONObject obj = new JSONObject();

      obj.put("name", "foo");
      obj.put("num",rs.getInt(1));
      obj.put("balance", rs.getString(2));
      obj.put("is_vip", rs.getString(3));

      System.out.print(obj);
于 2013-11-06T06:58:57.367 回答
0

你可以这样做:

...
JsonWriter writer = new JsonWriter(new OutputStreamWriter(res.getOutputStream(), "UTF-8"));
writer.beginArray();
while(rs.next())
{
writer.beginObject();
writer.name("DATA").value(rs.getString(1));
writer.name("VALUE").value(rs.getString(2));
writer.endObject();
}
writer.endArray();
writer.close();
....

这将从 db 中获取您的结果并将 json 表示形式放入响应输出流

于 2013-11-06T07:09:20.893 回答