如何将List<Map<String, Object>>转换为JSON字符串?寻求替代String.join的可行方案
String.join() Fails for List<Map<String, Object>> Let's break down the error first: String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements) only works with collections of objects that implement the CharSequence interface (like String does). Since Map<String, Object> doesn't implement this interface, the compiler can't resolve the method call—this is exactly why it works flawlessly for List<String>!
Manually building JSON strings (like you did with List<String>) is risky—you'll quickly hit issues with escaped characters, missing quotes, or edge cases you didn't account for. Instead, use a battle-tested JSON library like Jackson or Gson—these tools handle all the messy serialization logic for you.
Example with Jackson
First, add the Jackson dependency (for Maven projects):
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> <!-- Use the latest stable version --> </dependency>
Then serialize your list in just a few lines:
import com.fasterxml.jackson.databind.ObjectMapper; // ... List<Map<String, Object>> listOfMap = createListOfMap(count); ObjectMapper objectMapper = new ObjectMapper(); String jsonString = objectMapper.writeValueAsString(listOfMap);
This will automatically convert your List<Map> into a valid JSON array, handling all quoting, commas, and nested structure rules correctly.
Example with Gson
If you prefer Gson, add its dependency first:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.10.1</version> <!-- Use the latest stable version --> </dependency>
Then serialize your list like this:
import com.google.gson.Gson; // ... List<Map<String, Object>> listOfMap = createListOfMap(count); Gson gson = new Gson(); String jsonString = gson.toJson(listOfMap);
If you absolutely have to avoid external libraries (though I strongly advise against this for production code), you can convert each Map to a JSON-compatible string via streams, then join them:
import java.util.stream.Collectors; // ... String listAsString = listOfMap.stream() .map(map -> String.format("{\"productCode\":\"%s\",\"quantity\":%d}", map.get("productCode"), map.get("quantity"))) .collect(Collectors.joining(", ")); String stringAsJSON = "[" + listAsString + "]";
Heads up: This approach is fragile. If productCode ever contains special characters (like quotes, backslashes, or newlines), your JSON will be invalid. Stick to a proper library for reliable results.
内容的提问来源于stack exchange,提问作者Kapparino

