如何将JSON响应返回的列表转换为带引号的逗号分隔字符串
实现方案
方案1:JSON解析库实现(推荐,无兼容性问题)
这是最稳妥的实现方式,不会因为元素内容包含方括号、逗号等特殊符号出现处理错误,可适配所有标准JSON数组格式。
Gson版本
如果项目使用Gson作为JSON解析工具:
import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.List; import java.util.stream.Collectors; // 解析JSON数组为字符串列表 Gson gson = new Gson(); List<String> fruitList = gson.fromJson(fruits, new TypeToken<List<String>>(){}.getType()); // 拼接为目标格式 String target = fruitList.stream() .map(item -> "\"" + item + "\"") .collect(Collectors.joining(", "));
Jackson版本
如果项目使用Jackson作为JSON解析工具:
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List; import java.util.StringJoiner; // 解析JSON数组为字符串列表 ObjectMapper objectMapper = new ObjectMapper(); List<String> fruitList = objectMapper.readValue(fruits, new TypeReference<List<String>>() {}); // 拼接为目标格式 StringJoiner joiner = new StringJoiner(", "); for (String item : fruitList) { joiner.add("\"" + item + "\""); } String target = joiner.toString();
方案2:简易字符串截取实现(仅适用于格式固定场景)
如果确认返回的JSON数组格式标准,且元素内容不会包含[、]、,等特殊符号,可以直接用字符串操作实现,无需引入额外依赖:
if (fruits != null && fruits.startsWith("[") && fruits.endsWith("]")) { // 去除首尾方括号 String content = fruits.substring(1, fruits.length() - 1); // 把逗号替换为逗号+空格 String target = content.replace(",", ", "); }
注意:该方案存在兼容风险,如果元素内容本身包含逗号、方括号会导致输出结果异常,仅可用于后端返回格式完全可控的场景。
内容的提问来源于stack exchange,提问作者Abhishek
相关产品推荐
相关产品推荐

