Mysql
 sql >> Database >  >> RDS >> Mysql

Converti l'oggetto contenente campi ripetuti in JSON

Puoi utilizzare Gson di Google in questo caso:

public String getJSONFromResultSet(ResultSet rs, String key) {
    Map json = new HashMap();
    List list = new ArrayList();
    if (rs != null) {
        try {
            ResultSetMetaData mData = rs.getMetaData();
            while (rs.next()) {
                Map<String, Object> columns = new HashMap<String, Object>();
                for (int columnIndex = 1; columnIndex <= mData.getColumnCount(); columnIndex++) {
                    if (rs.getString(mData.getColumnName(columnIndex)) != null) {
                        columns.put(mData.getColumnLabel(columnIndex),
                                rs.getString(mData.getColumnName(columnIndex)));
                    } else {
                        columns.put(mData.getColumnLabel(columnIndex), "");
                    }
                }
                list.add(columns);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        json.put(key, list);
    }
    return new Gson().toJson(json);
}

Aggiornamento: Puoi chiamare getJSONFromResultSet metodo come di seguito:

Connection con = DBConnectionClass.myConnection();
        PreparedStatement ps = con.prepareStatement("SELECT * FROM Customer");
      //as an example consider a table named Customer in your DB.
        ResultSet rs = ps.executeQuery();
        System.out.println(getJSONFromResultSet(rs, "customer"));