List转json 顺序不一致

new JSONObject()方法使返回的json格式数据的顺序与list集合中的数据顺序保持一致

原因在于json版本问题

json2.1以前源码中new JsonOjbect()中的构建函数是

public JSONObject()
  {
    this.properties = new HashMap();
  }

而在2.3版本后源码为:

public JSONObject()
  {
    this.properties = new ListOrderedMap();
  }

ListOrderedMap位于commons-collections的jar包里,与普通的map相比,ListOrderedMap的key可保持原有顺序,而hashmap是无序的

项目需求:

      将mysql表中的所有字段名和字段注释,表名,表描述用json返回

     表名和秒描述在一张表中展示e_move

// 获取所有需要导出的表名
    public static String getTableInfoBeanJson() {
       JSONArray jsonarray = new JSONArray();
        Connection conn = DbHelper.getConnection();
        ResultSet rs = null;
        PreparedStatement ps = null;
        try {
            ps = DbHelper.getConnection().prepareStatement("select * from e_move");

            rs = ps.executeQuery();
            while (rs.next()) {
                JSONObject jsonobj = new JSONObject();
                String tableName = rs.getString("table_name");
                String tableDesc = rs.getString("desc");
                List<ColumnBean> colList = readTableColumn(conn, tableName);
                jsonobj.put("target", tableName);
                jsonobj.put("name", tableDesc);
                jsonobj.put("element", colList);
                jsonarray.add(jsonobj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DbHelper.Close(rs, ps, conn);
        }

        return jsonarray.toString();
    }

//获取表中字段
    public static List<ColumnBean> readTableColumn(Connection conn, String tableName) {
        List<ColumnBean> colList = new ArrayList<ColumnBean>();
        ResultSet resultSet = null;
        try {
            DatabaseMetaData dbmd = conn.getMetaData();
            resultSet = dbmd.getTables(null, "%", "%", new String[] {"TABLE"});
            while (resultSet.next()) {
                String t1 = resultSet.getString("TABLE_NAME");
                ResultSet rs = dbmd.getColumns(null, "%", tableName, "%");
                if (t1.contains(tableName)) {
                    while (rs.next()) {
                        ColumnBean col = new ColumnBean();
                        col.setName(rs.getString("REMARKS"));
                        col.setEname(rs.getString("COLUMN_NAME"));
                        colList.add(col);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DbHelper.Close(resultSet, null, null);
        }

        return colList;
    }

 ColumnBean.java

public class ColumnBean {
    private String ename; //字段名
    private String name; //注释
    public String getEname() {
        return ename;
    }
    public void setEname(String ename) {
        this.ename = ename;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
   
    
    
    

}

注意:用json2.3版本后的,使用new JsonObject()则可以实现有序