如何用ObjectMapper或Java8 Stream处理JSON提取、格式化及拼接?
解决方案
1. 提取至"received": "success"的JSON字符串
用Jackson的API替代字符串截取,更可靠且不易出错,两种实现方式可选:
方式一:基于JsonParser精准截取原字符串片段
严格匹配原JSON格式,截取到"received": "success"的结尾位置:
import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import java.io.IOException; public String extractUntilReceivedSuccess(String originalJson) throws IOException { JsonFactory factory = new JsonFactory(); try (JsonParser parser = factory.createParser(originalJson)) { while (!parser.isClosed()) { JsonToken token = parser.nextToken(); if (JsonToken.FIELD_NAME.equals(token) && "received".equals(parser.getCurrentName())) { parser.nextToken(); // 跳转到字段值位置 if ("success".equals(parser.getValueAsString())) { // 截取原字符串到当前token的末尾 return originalJson.substring(0, parser.getCurrentLocation().getCharOffset()); } } } throw new IllegalArgumentException("JSON中未找到\"received\": \"success\""); } }
方式二:基于JsonNode序列化目标片段
允许重新序列化后的格式与原JSON略有差异(如空格),实现更简洁:
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; import java.util.Iterator; import java.util.Map; public String extractUntilReceivedSuccess(ObjectMapper mapper, String originalJson) throws IOException { JsonNode rootNode = mapper.readTree(originalJson); ObjectNode resultNode = mapper.createObjectNode(); Iterator<Map.Entry<String, JsonNode>> fieldIterator = rootNode.fields(); while (fieldIterator.hasNext()) { Map.Entry<String, JsonNode> entry = fieldIterator.next(); resultNode.set(entry.getKey(), entry.getValue()); // 找到received字段后停止遍历 if ("received".equals(entry.getKey())) { break; } } return mapper.writeValueAsString(resultNode); }
2. 拼接处理后的字段
推荐用JsonNode拼接,避免手动字符串拼接的格式错误:
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; import java.util.List; public String assembleFinalResult(String extractedJson, List<String> formattedComments, String timestamp, String notification) throws IOException { ObjectMapper mapper = new ObjectMapper(); JsonNode baseNode = mapper.readTree(extractedJson); // 将额外字段添加到基础JSON节点 ((ObjectNode) baseNode) .set("comments", mapper.valueToTree(formattedComments)) .put("timestamp", timestamp) .put("notification", notification); // 可选:格式化输出JSON return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(baseNode); }
3. 用Java8 Stream处理Comment
完全可以替代indexOf/lastIndexOf实现过滤和格式化,示例如下:
import java.util.List; import java.util.stream.Collectors; public List<String> processComments(List<String> rawComments) { return rawComments.stream() // 过滤空或空白评论 .filter(comment -> comment != null && !comment.isBlank()) // 去除特殊字符(示例:保留字母、数字、中文) .map(comment -> comment.replaceAll("[^a-zA-Z0-9\\u4e00-\\u9fa5]", "")) // 去除前后空格 .map(String::trim) // 收集为处理后的列表 .collect(Collectors.toList()); }
如果是单个字符串类型的comment,可转为流处理:
import java.util.stream.Collectors; public String processSingleComment(String rawComment) { if (rawComment == null || rawComment.isBlank()) { return ""; } return rawComment.chars() .filter(c -> Character.isLetterOrDigit(c) || Character.isIdeographic(c)) .mapToObj(c -> String.valueOf((char) c)) .collect(Collectors.joining()) .trim(); }
内容的提问来源于stack exchange,提问作者jen
相关产品推荐
相关产品推荐

