我正在尝试实现一个 Servlet,它生成 JSON 的方式与此 php 脚本相同:
$response->page = $page;
$response->total = $total_pages;
$response->records = $count;
$i=0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
/*
$response->rows[$i]['id']=$row[id];
$response->rows[$i]['cell']=array($row[id],$row[invdate],$row[name],$row[amount],$row[tax],$row[total],$row[note]);
*/
$response->rows[$i]['id']=$row['id'];
$response->rows[$i]['name']=$row['name'];
$response->rows[$i]['author']=$row['author'];
//$response->rows[$i]=array($row[id],$row[invdate],$row[name],$row[amount],$row[tax],$row[total],$row[note]);
$i++;
}
echo json_encode($response);
正确的 json 输出应该是这样的:
{"page":null,"total":0,"records":"68","rows":[{"id":"1","name":"Thinking in Java","author":null},{"id":"4","name":"Effective Java: A Programming Language Guide","author":"Joshua Bloch"},{"id":"5","name":"Learn Java for Android Development","author":"Jeff Friesen"}]}
我以这种方式尝试过,但它似乎产生了另一个输出:
JsonArray jArray = new JsonArray();
JsonObject jo = new JsonObject();
jo.addProperty("page", page);
jo.addProperty("total", totalPageString);
jo.addProperty("records", count);
jArray.add(jo);
int i = 0;
try {
while (rs2.next()) {
JsonObject tmp = new JsonObject();
tmp.addProperty("rows[" + i + "]['lastname']", rs2.getString(1));
tmp.addProperty("rows[" + i + "]['firstname']",
rs2.getString(2));
tmp.addProperty("rows[" + i + "]['staffnumber']",
rs2.getString(3));
jArray.add(tmp);
i++;
}
} catch (SQLException e) {
e.printStackTrace();
}
response.setContentType("application/Json");
response.getWriter().print(jArray);
我的输出如下所示:
[{"page":"0","total":"Infinity","records":2},{"lastname":"Hanke","firstname":"Jannis","staffnumber":"9395835"},{"lastname":"Hanke","firstname":"Jannis","staffnumber":"83833"}]
rs2 是一个包含数据库数据的结果集。php 代码来自 jquery combogrid 插件的示例页面。
我真的不明白这个工作。有人可以帮帮我吗?