如何将Java对象转换为Json对象并放入json数组中

时间:2017-03-07 11:53:30

标签: java json ajax servlets web-deployment

我想点击按钮进行ajax调用。这将从mysql中获取记录并将放入employee对象。现在我想将员工对象数组发送回我的ajax调用。所以想到使用JSON。 package com;这段代码工作正常,但我无法使用Employee类及其对象。我直接使用JSON及其工作。

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SelectUsers {
    public JSONArray selectQueryDemo() throws SQLException
    {
        GlobalConnection gc=new GlobalConnection();
        Connection conn=gc.getConnection();
        Statement s=conn.createStatement();
        ResultSet result=s.executeQuery("select * from tblemployees");
        String name = "";
        JSONArray jsonArray = new JSONArray();
        while(result.next())
        {
            JSONObject obj = new JSONObject();
            try {
                obj.put("id", result.getInt(1));
                obj.put("name", result.getString(2));
                obj.put("gender", result.getString(3));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            jsonArray.put(obj);
        }
        return jsonArray;
    }
}

1 个答案:

答案 0 :(得分:0)