使用gson在JSP页面中序列化POJO时,输出为空。我错过了什么?

时间:2015-09-30 22:11:23

标签: java json jsp serialization gson

我有一个运行数据库查询的JSP页面,并将结果序列化为JSON。我序列化的对象是:

class DataObject {
    private int iTotalRecords;
    private int iTotalDisplayRecords;
    private String sEcho;
    private ArrayList<String> columns;
    private ArrayList<ArrayList<String>> data;
    //getter and setter methods

    public void setColumns( ArrayList<String> cols ) {
        columns = cols;
    }

    public void setTotalDisplayRecords( int _numrecs ) {
        iTotalDisplayRecords = _numrecs;
    }

    public void setTotalRecords( int _numrecs ) {
        iTotalRecords = _numrecs;
    }

    public void setData( ArrayList<ArrayList<String>> _data ) {
        data = _data;
    }

    public void setEcho( String _echo ) {
        sEcho = _echo;
    }

    @Override
    public String toString() {
        return "DataObject [iTotalRecords=" + iTotalRecords + 
            ", iTotalDisplayRecords=" + iTotalDisplayRecords + 
            ", sEcho=" + sEcho + 
            ", columns=" + columns +
            ", data=" + data + "]";
    }

    public DataObject() {
        this.sEcho = "1";
        this.iTotalDisplayRecords = 0;
        this.iTotalRecords = 0;
        this.columns = new ArrayList<String>();
        this.data = new ArrayList<ArrayList<String>>();
    }
}

我简化了页面,JSP(仍然生成空白JSON)如下所示:

String queryOvr = "select 'error' as Input_Parameters";
String sEcho = "0";
LOG.error("db_json_test.jsp - QUERY: " + queryOvr);

int rowCount=0;
int totalCount=0;
Statement stmt = null;
ResultSet returnData = null;
Connection conn = null;
try {
    conn = DatabaseUtilities.getConnection();  //proprietary connection pool of host application
    stmt = conn.createStatement();
    returnData = stmt.executeQuery(queryOvr);
    ResultSetMetaData rsmd = returnData.getMetaData();
    DataObject dObj = new DataObject();

    ArrayList<String> headerRow = new ArrayList<String>();
    int colCount = rsmd.getColumnCount();
    // write column names
    for (int i=0; i<colCount; i++) {
        String headerName = rsmd.getColumnName(i+1);
        if ("".equals(headerName)) {
            headerName = "Column-" + String.valueOf(i+1);
        }
        LOG.error("db_json_test.jsp - HEADER: " + headerName);
        headerRow.add(headerName);
    }
    dObj.setColumns(headerRow);

    // write data
    ArrayList<ArrayList<String>> dataArray = new ArrayList<ArrayList<String>>();
    while ( returnData.next() ) {
        rowCount++;
        ArrayList<String> dataRow = new ArrayList<String>();
        for (int i=0; i<colCount; i++){ 
            String dbData = returnData.getString(i+1);
            LOG.error("db_json_test.jsp - DATA: row: " + headerRow.get(i) + ", value: " + dbData);
            dataRow.add(dbData);
        }
        dataArray.add(dataRow);
        totalCount++;
    }
    dObj.setData(dataArray);

    dObj.setEcho(sEcho);
    dObj.setTotalRecords(totalCount);
    dObj.setTotalDisplayRecords(rowCount);

    LOG.error("db_json_test.jsp - OBJ: " + dObj.toString());
    Type typeResults = new TypeToken<DataObject>(){}.getType();
    Gson gson = new Gson();
    String json = gson.toJson(dObj, typeResults);
    LOG.error("db_json_test.jsp - JSON: " + json);

    //gson.toJson(dObj, typeResults, response.getWriter());
    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().write(json);
    response.getWriter().flush();
    response.getWriter().close();
}
catch (Throwable t) {
    LOG.error("db_json.jsp - Error: " + t.toString());
    //t.printStackTrace();

    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().write("{\"error\":\"" + t.toString() + "\"}");
    response.getWriter().flush();
    response.getWriter().close();
}

当我查看日志时,我可以看到DataObject实例已正确填充:

783167943 30 Sep 2015 17:37:51,924 ERROR [http-8500-1] JSP            - db_json_test.jsp - QUERY: select 'error' as Input_Parameters
783167959 30 Sep 2015 17:37:51,940 ERROR [http-8500-1] JSP            - db_json_test.jsp - HEADER: Input_Parameters
783167959 30 Sep 2015 17:37:51,940 ERROR [http-8500-1] JSP            - db_json_test.jsp - DATA: row: Input_Parameters, value: error
783167959 30 Sep 2015 17:37:51,940 ERROR [http-8500-1] JSP            - db_json_test.jsp - OBJ: DataObject [iTotalRecords=1, iTotalDisplayRecords=1, sEcho=0, columns=[Input_Parameters], data=[[error]]]
783167959 30 Sep 2015 17:37:51,940 ERROR [http-8500-1] JSP            - db_json_test.jsp - JSON: 

然而,当我使用gson.toJson(dObj)进行序列化时,我得到一个空字符串。我已经尝试指定上面示例中显示的类型没有不同的结果。除了我可能不应该在JSP文件中执行此操作的论点之外,我在这里缺少什么?

值得注意的是,catch例程确实将错误消息作为有效的JSON返回,因此在头文件中正确设置了contentType和charset。

以下Java代码生成了预期的JSON ...

public class gsonTest {

    class DataObject {
        private int iTotalRecords;
        private int iTotalDisplayRecords;
        private String sEcho;
        private ArrayList<String> columns;
        private ArrayList<ArrayList<String>> data;

        // getter and setter methods

        public void setColumns(ArrayList<String> cols) {
            columns = cols;
        }

        public void setTotalDisplayRecords(int _numrecs) {
            iTotalDisplayRecords = _numrecs;
        }

        public void setTotalRecords(int _numrecs) {
            iTotalRecords = _numrecs;
        }

        public void setData(ArrayList<ArrayList<String>> _data) {
            data = _data;
        }

        public void setEcho(String _echo) {
            sEcho = _echo;
        }

        @Override
        public String toString() {
            return "DataObject [iTotalRecords=" + iTotalRecords
                    + ", iTotalDisplayRecords=" + iTotalDisplayRecords
                    + ", sEcho=" + sEcho 
                    + ", columns=" + columns 
                    + ", data=" + data + "]";
        }

        public DataObject() {
            this.sEcho = "";
            this.iTotalDisplayRecords = 0;
            this.iTotalRecords = 0;
            this.columns = new ArrayList<String>();
            this.data = new ArrayList<ArrayList<String>>();
        }
    }

    public static void main(String[] args) {
        int totalCount = 0;
        String sEcho = "1";
        Gson gson = new Gson();
        gsonTest tst = new gsonTest();

        Type typeResults = new TypeToken<DataObject>(){}.getType();

        DataObject obj = tst.new DataObject();

        ArrayList<String> headerRow = new ArrayList<String>();
        // write column names
        int colCount = 2;
        for (int i = 0; i < colCount; i++) {
            headerRow.add("Column-" + String.valueOf(i));
        }
        obj.setColumns(headerRow);

        // write data
        ArrayList<ArrayList<String>> dataArray = new ArrayList<ArrayList<String>>();
        int rowCount = 0;
        while (rowCount < 20) {
            ArrayList<String> dataRow = new ArrayList<String>();
            for (int i = 0; i < colCount; i++) {
                dataRow.add("Row-" + String.valueOf(rowCount) + ":Col-"
                        + String.valueOf(i));
            }
            rowCount++;
            dataArray.add(dataRow);
            totalCount++;
        }
        obj.setData(dataArray);

        obj.setEcho(sEcho);
        obj.setTotalRecords(totalCount);
        obj.setTotalDisplayRecords(rowCount);
        String output = gson.toJson(obj,typeResults);
        System.out.println(obj.toString());
        System.out.println(output);
    }
}

这是输出:

  

DataObject [iTotalRecords = 20,iTotalDisplayRecords = 20,sEcho = 1,   columns = [Column-0,Column-1],data = [[Row-0:Col-0,Row-0:Col-1],   [Row-1:Col-0,Row-1:Col-1],[Row-2:Col-0,Row-2:Col-1],[Row-3:Col-0,   第3行:第1行],[第4行:第0列,第4行:第1列],[第5行:第0列,第5行:第1列],   [Row-6:Col-0,Row-6:Col-1],[Row-7:Col-0,Row-7:Col-1],[Row-8:Col-0,   第8行:第1行],[第9行:第0行,第9行:第1列],[第10行:第0行,   第10行:第1行],[第11行:第0行,第11行:第1列],[第12行:第0行,   第12行:第1行],[第13行:第0列,第13行:第1列],[第14行:第0行,   第14行:第1行],[第15行:第0行,第15行:第1列],[第16行:第0行,   第16行:第1行],[第17行:第0行,第17行:第1列],[第18行:第0行,   第18行:第1栏],[第19行:第0栏,第19行:第1栏]]           {&#34; iTotalRecords&#34;:20,&#34; iTotalDisplayRecords&#34;:20,&#34; sEcho&#34;:&#34; 1&#34;&#34;列&#34 ;: [&#34;柱-0&#34;&#34;色谱柱-1&#34],&#34;数据&#34;:[[&#34;行-0:Col-0中&#34 ;, &#34;行-0:的Col-1&#34;],[&#34;行-1:Col-0中&#34;&#34;行-1:的Col-1&#34;],[& #34;行-2:Col-0中&#34;&#34;行-2:山口-1&#34;],[&#34;行-3:Col-0中&#34;&#34;行3:的Col-1&#34;],[&#34;行4:Col-0中&#34;&#34;行4:的Col-1&#34;],[&#34;行-5:Col-0中&#34;&#34;行-5:的Col-1&#34;],[&#34;行-6:Col-0中&#34;&#34;行-6: COL-1&#34;],[&#34;行-7:Col-0中&#34;&#34;行-7:COL-1&#34;],[&#34;行-8:山口-0&#34;&#34;行-8:的Col-1&#34;],[&#34;行-9:Col-0中&#34;&#34;行-9:的Col-1&# 34],[&#34;行-10:Col-0中&#34;&#34;行-10:的Col-1&#34;],[&#34;行-11:Col-0中&#34 ;,&#34;行-11:的Col-1&#34;],[&#34;行-12:Col-0中&#34;&#34;行-12:的Col-1&#34], [&#34;行-13:Col-0中&#34;&#34;行-13:的Col-1&#34;],[&#34;行-14:Col-0中&#34;&# 34;行-14:的Col-1&#34;],[&#34;行-15:Col-0中&#34;&#34;行-15:的Col-1&#34;],[&#34 ;行16:Col-0中&#34;&#34;行-16:的Col-1&#34;],[&#34;行-17:Col-0中&#34;&#34;行向17:同事1&#34;],[&#34;行-18:Col-0中&#34;&#34;行-18:的Col-1&#34;],[&#34;行-19:Col-0中与#34;&#34;行-19:的Col-1&#34;]]}

1 个答案:

答案 0 :(得分:0)

进一步挖掘后,我找到了一个可行的解决方案。通过将测试Java类组合到JSP中,我得到了正确的输出。我不确定为什么这有效,原来没有

<%@ page
   language="java"
   session="true"
   contentType="application/json; charset=UTF-8"
%>
<%@ page import="com.google.gson.Gson,
                java.lang.reflect.Type,
                com.google.gson.reflect.TypeToken,
                java.util.ArrayList,
                java.sql.*,
                org.apache.log4j.Category,
                com.foo.bar.*;"
%>
<% 
final org.apache.log4j.Category LOG = org.apache.log4j.Category.getInstance ("JSP");

class db_json {

    class DataObject {
        private int iTotalRecords;
        private int iTotalDisplayRecords;
        private String sEcho;
        private ArrayList<String> columns;
        private ArrayList<ArrayList<String>> data;

        // getter and setter methods

        public void setColumns(ArrayList<String> cols) {
            columns = cols;
        }

        public void setTotalDisplayRecords(int _numrecs) {
            iTotalDisplayRecords = _numrecs;
        }

        public void setTotalRecords(int _numrecs) {
            iTotalRecords = _numrecs;
        }

        public void setData(ArrayList<ArrayList<String>> _data) {
            data = _data;
        }

        public void setEcho(String _echo) {
            sEcho = _echo;
        }

        @Override
        public String toString() {
            return "DataObject [iTotalRecords=" + iTotalRecords
                    + ", iTotalDisplayRecords=" + iTotalDisplayRecords
                    + ", sEcho=" + sEcho 
                    + ", columns=" + columns 
                    + ", data=" + data + "]";
        }

        public DataObject() {
            this.sEcho = "";
            this.iTotalDisplayRecords = 0;
            this.iTotalRecords = 0;
            this.columns = new ArrayList<String>();
            this.data = new ArrayList<ArrayList<String>>();
        }
    }

    public String testJson(HttpServletRequest request){
        String queryOvr = "select 'error' as Input_Parameters";
        LOG.debug("db_json3.jsp - QUERY: " + queryOvr);
        Gson gson = new Gson();
        int rowCount=0;
        int totalCount=0;
        Statement stmt = null;
        ResultSet returnData = null;
        Connection conn = null;
        try {
            conn = DatabaseUtilities.getConnection();
                stmt = conn.createStatement();
                returnData = stmt.executeQuery(queryOvr);
                ResultSetMetaData rsmd = returnData.getMetaData();
                DataObject dObj = new DataObject();

                ArrayList<String> headerRow = new ArrayList<String>();
                int colCount = rsmd.getColumnCount();
                // write column names
                for (int i=0; i<colCount; i++) {
                    String headerName = rsmd.getColumnName(i+1);
                    if ("".equals(headerName)) {
                        headerName = "Column-" + String.valueOf(i+1);
                    }
                    LOG.debug("db_json3.jsp - HEADER: " + headerName);
                    headerRow.add(headerName);
                }
                dObj.setColumns(headerRow);

                // write data
                ArrayList<ArrayList<String>> dataArray = new ArrayList<ArrayList<String>>();
                while ( returnData.next() ) {
                    if ( rowCount>=iDisplayStart && iDisplayLength>=0 && rowCount<iDisplayLength ) {
                        rowCount++;
                        ArrayList<String> dataRow = new ArrayList<String>();
                        for (int i=0; i<colCount; i++){ 
                            String dbData = returnData.getString(i+1);
                            LOG.debug("db_json3.jsp - DATA: row: " + headerRow.get(i) + ", value: " + dbData);
                            dataRow.add(dbData);
                        }
                        dataArray.add(dataRow);
                    }
                    totalCount++;
                }
                dObj.setData(dataArray);

                dObj.setEcho(sEcho);
                dObj.setTotalRecords(totalCount);
                dObj.setTotalDisplayRecords(rowCount);

                LOG.debug("db_json3.jsp - OBJ: " + dObj.toString());
                Type typeResults = new TypeToken<DataObject>(){}.getType();
                String json = gson.toJson(dObj, typeResults);
                LOG.debug("db_json3.jsp - JSON: " + json);
                return json;
        }
        catch (Throwable t) {
            LOG.debug("db_json3.jsp - Error: " + t.toString());
            return gson.toJson(t);
        }
    }
}
db_json dbjson = new db_json();
String json = dbjson.testJson();
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().write(json);
response.getWriter().flush();
response.getWriter().close();
%>