Servlet的JSON输出具有(不合需要的)任意顺序的SQL表列数据

时间:2017-01-02 15:02:59

标签: java mysql

我的servlet以任意顺序返回表列数据。我希望它按照模式中定义列的顺序返回列数据,或者至少为客户端提供确定正确顺序的方法。

MySQL Workbench screenshot of column default order

请注意,在上面的架构中,列顺序为: person_id,firstname,lastname,fullname

但是servlet正在返回带有不同顺序列的JSON字符串:

{"data":[{"LASTNAME":"Leonard","PERSON_ID":"0","FIRSTNAME":"Erick","FULLNAME":"Erick Leonard"}]}

下面是发出SQL命令的DAO bean和检索JSON的bean。

DAO Bean

package com.queryData.dao;

import com.queryData.dbconnection.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class DataDAO {
    DbConnection dbcon = new DbConnection();
    private static final String SQL = "select * from person";
    Connection con = null;
    PreparedStatement pst = null;
    ResultSet resultSet = null;

    public ResultSet getResultSet() {
        try {
            con = dbcon.setConnection();
            pst = con.prepareStatement(SQL);
            resultSet = pst.executeQuery();
        } catch (Exception ex) {
            System.out.println("Some Thing Went Wrong In getResultSet()");
            ex.printStackTrace();
        }
        return resultSet;
    }
}

检索列的Bean

package com.queryData.services;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONObject;

public class JsonServices {
    public static List<JSONObject> getFormattedResult(ResultSet rs) {
         List<JSONObject> resList = new ArrayList<JSONObject>();        

        try {
            ResultSetMetaData rsMeta = rs.getMetaData();
            int columnCnt = rsMeta.getColumnCount();
            List<String> columnNames = new ArrayList<String>();

            for (int i = 1; i <= columnCnt; i++) {

                // adding all retrieved column names to List object

                columnNames.add(rsMeta.getColumnName(i).toUpperCase());
            }

            while (rs.next()) {

                // convert each object to an human readable JSON object

                JSONObject obj = new JSONObject();
                for (int i = 1; i <= columnCnt; i++) {
                    String key = columnNames.get(i - 1);
                    String value = rs.getString(i);
                    obj.put(key, value);
                }
                resList.add(obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return resList;
    }
}

0 个答案:

没有答案