Java Spring Boot中高效搜索JSON字符串并返回匹配子集的方法
实现Java Spring Boot中JSON数组的模糊匹配过滤需求
需求场景
我正在开发Java Spring Boot应用,有如下格式的JSON数据:
{"version": "1.0.2","students": ["John Smith", "John Green", "Martin King"],"teachers": ["John Lord", "Martin Evans", "Steve John", "Gordon Lee", "Leo Martin"],"authors" : ["Martin Fowler", "Erich Gamma"]}
需要实现:输入指定搜索字符串,仅保留各数组中匹配的条目(忽略大小写),最终返回结构一致的JSON。例如搜索"mart"时,返回结果:
{"version": "1.0.2","students": ["Martin King"],"teachers": ["Martin Evans", "Leo Martin"],"authors" : ["Martin Fowler"]}
高效实现方案
1. 定义对应JSON的实体类
用Lombok简化实体类编写(也可手动实现getter/setter):
import lombok.Data; import java.util.List; @Data public class DataContainer { private String version; private List<String> students; private List<String> teachers; private List<String> authors; }
2. 编写过滤逻辑
利用Spring Boot默认集成的Jackson库完成JSON序列化/反序列化,同时实现数组模糊匹配过滤:
import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.stereotype.Component; import java.util.List; import java.util.stream.Collectors; @Component public class JsonFilterService { private final ObjectMapper objectMapper; // 注入Spring默认的ObjectMapper实例 public JsonFilterService(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } public String filterJson(String originalJson, String searchKeyword) throws Exception { // 1. 将JSON反序列化为实体类对象 DataContainer container = objectMapper.readValue(originalJson, DataContainer.class); // 2. 对每个数组字段进行过滤(忽略大小写) String lowerKeyword = searchKeyword.toLowerCase(); container.setStudents(filterList(container.getStudents(), lowerKeyword)); container.setTeachers(filterList(container.getTeachers(), lowerKeyword)); container.setAuthors(filterList(container.getAuthors(), lowerKeyword)); // 3. 将过滤后的对象序列化为JSON字符串返回 return objectMapper.writeValueAsString(container); } // 通用过滤方法:保留列表中包含指定关键字的元素(忽略大小写) private List<String> filterList(List<String> list, String lowerKeyword) { if (list == null || list.isEmpty()) { return list; } return list.stream() .filter(item -> item.toLowerCase().contains(lowerKeyword)) .collect(Collectors.toList()); } }
3. 使用示例
在Controller中调用该服务:
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class JsonFilterController { private final JsonFilterService filterService; public JsonFilterController(JsonFilterService filterService) { this.filterService = filterService; } @PostMapping("/filter-json") public String filterJson(@RequestBody String originalJson, @RequestParam String keyword) throws Exception { return filterService.filterJson(originalJson, keyword); } }
方案优势
- 复用Spring Boot原生Jackson库,无需额外引入依赖,兼容性强
- 采用Stream API过滤,代码简洁高效
- 通用过滤方法可复用,后续新增数组字段只需添加对应setter调用即可
内容的提问来源于stack exchange,提问作者ambuli
相关产品推荐
相关产品推荐

