【发布时间】:2017-05-13 16:42:08
【问题描述】:
这是 MySql 表的内容。如何使用 JSP 以 JSON 格式获取此结果。
name child name child name1 child color
parent null null null
null c1 red
null c11 blue
null c12 red
null c2 pink
null c21 red
null c22 red
null c23 red
这是我的 JSP 代码
<%@ page import="java.sql.*" %>
<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<HEAD>
<TITLE>Fetching Data From a Database</TITLE>
</HEAD>
<H1>Fetching Data From a Database</H1>
<%
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost:3306/data","root","admin321");
Statement statement = con.createStatement();
String id = request.getParameter("name");
ResultSet resultset =
statement.executeQuery("select * from newnew") ;
if(!resultset.next()) {
out.println("Sorry, could not find . ");
} else {
%>
<%
}
%>
[
<% while (resultset.next()) { %>
{ "name": "<%= resultset.getString("name") %>" ,
"children": [{ "name": "<%= resultset.getString
("child name") %>", "color":
"<%= resultset.getString("child color") %>" , "children" : [
{ "name": "<%= resultset.getString("child name1") %>",
"color": "<%= resultset.getString("child color") %>"
}
]}
<% } %>
这显示格式错误,如果我将它用于它显示的另一个表。
[{ “姓名”:“父母”, “孩子们”: [{ “名称”:“c1”, “红色” }],{ “姓名”:“父母”, “红色”, “孩子们”: [{ “名称”:“c11”, “红色” }] },
}]
我想变成这样。
[
{
"name":"parent",
"children":[
{
"name":"c1",
"color":"red",
"children":[
{
"name":"c11",
"color":"red"
},
{
"name":"c12",
"color":"red"
}
]
},
{
"name":"c2",
"color":"orange",
"children":[
{
"name":"c21",
"color":"red"
},
{
"name":"c22",
"color":"red"
},
{
"name":"c23",
"color":"green"
},
}
]
【问题讨论】: