如何在Java中创建包含不同数据类型的Map列表?
Hey there! No worries at all about your Java basics—we all start somewhere, and it’s totally okay to ask these questions. Let’s walk through exactly how to turn your ResultSet into a list of maps that you can easily convert to JSON.
First, let’s clarify what we’re building: we want to take every row from your ResultSet, turn it into a HashMap<String, Object> (where the keys are your database column names, and the values are the corresponding row data—supporting all different data types like strings, integers, dates, etc.), then collect all these maps into a List that we can serialize to JSON.
To convert our list to JSON, we’ll use Jackson—the most popular JSON library for Java. If you’re using Maven, add this dependency to your pom.xml:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> <!-- Use the latest stable version here --> </dependency>
If you’re using Gradle, add this to your build.gradle:
implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2'
Here’s a complete, commented code example that does this. We’ll use try-with-resources to auto-close database resources (super important to avoid leaks!) and ResultSetMetaData to dynamically get column names (so you don’t have to hardcode them):
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class ResultSetToListExample { public static void main(String[] args) { // Replace these with your database details String dbUrl = "jdbc:mysql://localhost:3306/your_database_name"; String dbUser = "your_username"; String dbPassword = "your_password"; String query = "SELECT * FROM your_table_name"; List<HashMap<String, Object>> resultList = new ArrayList<>(); try (Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query)) { // Get metadata to fetch column names dynamically ResultSetMetaData metaData = rs.getMetaData(); int totalColumns = metaData.getColumnCount(); // Iterate over each row in the ResultSet while (rs.next()) { HashMap<String, Object> rowMap = new HashMap<>(); // Loop through each column in the current row for (int i = 1; i <= totalColumns; i++) { String columnName = metaData.getColumnName(i); // Use getObject() to handle all data types automatically Object columnValue = rs.getObject(i); rowMap.put(columnName, columnValue); } // Add the row's map to our list resultList.add(rowMap); } } catch (Exception e) { // Handle any errors (you might want to log this instead of printing) e.printStackTrace(); } // Now resultList holds all your data in the structure you need! } }
Key Notes About This Code:
rs.getObject(i)works for all data types (varchar, int, date, etc.)—it’ll return the appropriate Java object (String, Integer, java.sql.Date, etc.).- Using
ResultSetMetaDatameans you don’t have to update your code if you add/remove columns from your database table.
Once you have your List<HashMap<String, Object>>, converting it to JSON is straightforward with Jackson’s ObjectMapper:
import com.fasterxml.jackson.databind.ObjectMapper; import java.text.SimpleDateFormat; // ... (put this right after building resultList) ... ObjectMapper objectMapper = new ObjectMapper(); // Optional: Configure date formatting (so dates don't become timestamps) objectMapper.configure(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); // Optional: Ignore null values in the JSON output objectMapper.setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL); try { String jsonOutput = objectMapper.writeValueAsString(resultList); System.out.println(jsonOutput); // You can save this string to a file, send it over HTTP, etc. } catch (Exception e) { e.printStackTrace(); }
- If you get a "ClassNotFoundException" for Jackson classes, double-check your dependency setup—make sure the library is properly downloaded and included in your project.
- If date values look weird in the JSON, adjust the
SimpleDateFormatpattern to match what you need. - If you have custom database types, you might need to add Jackson modules to handle them (but for most standard types, the default setup works).
Hope this clears things up for you! Don’t hesitate to ask if you hit any snags along the way.
内容的提问来源于stack exchange,提问作者Shaonline

