这是我的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);
}
}
}
答案 0 :(得分: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);
答案 1 :(得分: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表示放入responce outputstream