0

我正在尝试实现一个 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 插件的示例页面。

我真的不明白这个工作。有人可以帮帮我吗?

4

1 回答 1

1

给定所需的 JSON,请考虑以下内容:

JsonObject jo = new JsonObject();
jo.addProperty("page", page);
jo.addProperty("total", totalPageString);
jo.addProperty("records", count);

JsonArray jArray = new JsonArray();
try {
    while (rs2.next()) {
        JsonObject row = new JsonObject();

        row.addProperty("id", rs2.getString(1));
        row.addProperty("name", rs2.getString(2));
        row.addProperty("author", rs2.getString(3));
        jArray.add(row);
    }
    jo.add("rows", jArray);
} catch (SQLException e) {
    e.printStackTrace();
}

response.setContentType("application/json");
response.getWriter().print(jo);

重要笔记:

  • 因为你有rs2结果集,所以rows消失了。您不希望将其作为字段名称的一部分。
  • 您可能会构建jArray并将其附加到对象上,而不是相反。
  • 请参阅此链接以获取正确的内容类型
于 2012-10-03T23:17:45.500 回答