在Java Servlet中生成JSON对象

时间:2012-10-03 23:04:45

标签: java jquery json servlets

我想要实现一个生成JSON的Servlet,就像这个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插件的示例页面。

我真的不懂这个。请有人帮帮我吗?

1 个答案:

答案 0 :(得分: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并将其附加到对象,而不是相反。
  • 请参阅this link了解正确的内容类型